Summary - Itertools
- Python course
- Intermediate
- Lesson 99/116
- 5 min
Combine chain, islice and groupby to write a log summarizer.
Summary - Itertools
In this group we covered chain, count/cycle, islice, combinations/permutations, and groupby. All come from the itertools module and work iterator-based.
chain merges, count/cycle give infinite iterators, islice slices, combinations/permutations produce selections, groupby makes consecutive groups. Now we'll write an example that combines a few of them.
Practice Combined summary example
Start with from itertools import chain, islice. Merge two lists and take the first three with result = list(islice(chain([1, 2], [3, 4]), 3)). Then print with print(result).
Starter code
# Combine chain and isliceSample solution
# Combine chain and islice
from itertools import chain, islice
result = list(islice(chain([1, 2], [3, 4]), 3))
print(result)Expected output
[1, 2, 3]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool produces an infinite iterator?
- chain
- islice
- groupby
- count Correct answer
Explanation: count produces infinitely increasing numbers.
2 Match the tool and its purpose
| Term | Meaning |
|---|---|
chain |
Merge |
islice |
Slice |
combinations |
Unordered selection |
groupby |
Grouping |
3 Import islice
from itertools import chain, ____
result = list(islice(chain([1, 2], [3, 4]), 3))
print(result)
from itertools import chain, islice
result = list(islice(chain([1, 2], [3, 4]), 3))
print(result)
Explanation: islice is also in the itertools module.
4 Match the summary example parts
| Term | Meaning |
|---|---|
chain |
Merges lists |
islice |
Takes first three |
list(...) |
Lists the result |
print(result) |
Prints |