Interview question
What is the itertools module and what are some commonly used functions from it? itertools module क्या है और इसके commonly used functions क्या हैं?
Answer
itertools is a standard library module providing fast, memory-efficient tools for working with iterators, covering common patterns like combinations, grouping, and infinite sequences.
| Function | Purpose |
|---|---|
| chain() | Combines multiple iterables into one sequence |
| count() | Infinite counting sequence |
| cycle() | Infinitely repeats an iterable |
| combinations() | All possible combinations of a given length |
| permutations() | All possible orderings of a given length |
| groupby() | Groups consecutive items by a key function |
from itertools import chain, count, cycle, combinations, permutations, groupby, islice
# chain - combine iterables
print(list(chain([1, 2], [3, 4]))) # [1, 2, 3, 4]
# count - infinite sequence, use islice to limit it
for i in islice(count(10, 2), 5): # start=10, step=2, limit 5 items
print(i) # 10, 12, 14, 16, 18
# cycle - infinite repetition, useful with islice
repeated = list(islice(cycle(['a', 'b']), 5))
print(repeated) # ['a', 'b', 'a', 'b', 'a']
# combinations - order doesn't matter
print(list(combinations([1, 2, 3], 2))) # [(1,2), (1,3), (2,3)]
# permutations - order matters
print(list(permutations([1, 2, 3], 2))) # [(1,2),(1,3),(2,1),(2,3),(3,1),(3,2)]
# groupby - groups CONSECUTIVE matching items (input should be sorted for full grouping)
data = [('fruit', 'apple'), ('fruit', 'banana'), ('veg', 'carrot')]
for key, group in groupby(data, key=lambda x: x[0]):
print(key, list(group))
# fruit [('fruit', 'apple'), ('fruit', 'banana')]
# veg [('veg', 'carrot')]itertools standard library module है जो iterators के साथ काम करने के लिए fast, memory-efficient tools देता है - combinations, grouping, infinite sequences जैसे common patterns cover करता है।
| Function | उद्देश्य |
|---|---|
| chain() | Multiple iterables combine करता है |
| count() | Infinite counting sequence |
| cycle() | Iterable को infinitely repeat करता है |
| combinations() | दिए गए length के सभी combinations |
| groupby() | Consecutive items को key से group करता है |
from itertools import chain, count, cycle, combinations, permutations, groupby, islice
print(list(chain([1, 2], [3, 4]))) # [1, 2, 3, 4]
for i in islice(count(10, 2), 5):
print(i) # 10, 12, 14, 16, 18
repeated = list(islice(cycle(['a', 'b']), 5))
print(repeated) # ['a', 'b', 'a', 'b', 'a']
print(list(combinations([1, 2, 3], 2))) # [(1,2), (1,3), (2,3)]
print(list(permutations([1, 2, 3], 2)))
data = [('fruit', 'apple'), ('fruit', 'banana'), ('veg', 'carrot')]
for key, group in groupby(data, key=lambda x: x[0]):
print(key, list(group))Was this answer clear?