Python `itertools` module

Prasad
3 min readMay 15, 2023

--

Here are 10 different methods from the Python `itertools` module that can make your code neater, cleaner, and better:

  1. `count(start=0, step=1)`: Returns an infinite iterator that generates an arithmetic progression starting from `start` and incrementing by `step` for each item. This method is useful when you need to generate a sequence of numbers that don’t have a definite endpoint.
from itertools import count
# Create an infinite iterator that generates even numbers
evens = count(start=0, step=2)
# Print the first 10 even numbers
for i in range(10):
print(next(evens))

2. `cycle(iterable)`: Repeats the elements of an iterable indefinitely. This method is useful when you need to cycle through a sequence of values repeatedly.

3. `chain(*iterables)`: Chains multiple iterables into a single iterable. This method is useful when you need to combine multiple sequences into a single sequence.

from itertools import chain

# Combine two lists into a single iterable
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = chain(list1, list2)

# Print the combined list
for item in combined:
print(item)

4. `compress(data, selectors)`: Filters elements from an iterable based on the values in a corresponding selector iterable. This method is useful when you need to filter an iterable based on some condition.

from itertools import compress

# Filter out odd numbers using a list of selectors
numbers = [1, 2, 3, 4, 5, 6]
selectors = [True, False, True, False, True, False]
filtered = compress(numbers, selectors)

# Print the filtered list
for item in filtered:
print(item)

5. `dropwhile(predicate, iterable)`: Drops elements from an iterable until the predicate function returns False, and then returns the remaining elements. This method is useful when you need to remove items from an iterable based on some condition.

from itertools import dropwhile

# Drop numbers from a list until a condition is met
numbers = [1, 2, 3, 4, 5, 6]
dropped = dropwhile(lambda x: x < 3, numbers)

# Print the remaining numbers
for item in dropped:
print(item)

6. `filterfalse(predicate, iterable)`: Returns an iterator over the elements in an iterable for which the predicate function returns False. This method is useful when you need to filter an iterable based on some condition, but want to keep the items that don’t satisfy the condition.

from itertools import filterfalse

# Filter out even numbers from a list of integers
numbers = [1, 2, 3, 4, 5, 6]
filtered = filterfalse(lambda x: x % 2 == 0, numbers)

# Print the filtered list
for item in filtered:
print(item)

7. `groupby(iterable, key=None)`: Groups the elements of an iterable based on a key function and returns an iterator that generates `(key, group)` pairs, where `key` is the grouping key and `group` is an iterator over the elements in the group. This method is useful when you need to group elements in an iterable based on some common property.

from itertools import groupby
# Group a list of words by their first letter
words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
groups = groupby(words, key=lambda x: x[0])
# Print the groups
for key, group in groups:
print(key, list(group))

8. `islice(iterable, start, stop[, step])`: Returns an iterator that generates elements from an iterable starting at `start`, up to (but not including) `stop`, with a step size of `step`. This method is useful when you need to generate a slice of an iterable.

from itertools import islice

# Extract a slice from a list
numbers = [1, 2, 3, 4, 5, 6]
sliced = islice(numbers, 2, 5)

# Print the sliced list
for item in sliced:
print(item)

9. `permutations(iterable, r=None)`: Generates all possible permutations of the elements in an iterable. This method is useful when you need to generate all possible arrangements of a set of items.

from itertools import permutations
# Generate all permutations of a string
string = 'abc'
perms = permutations(string)
# Print the permutations
for perm in perms:
print(''.join(perm))

10. `zip_longest(*iterables, fillvalue=None)`: Zips multiple iterables together, filling in missing values with a specified fill value. This method is useful when you need to combine iterables of unequal length, and want to fill in missing values with a default value.

from itertools import zip_longest
# Combine two lists of unequal length
numbers1 = [1, 2, 3, 4, 5]
numbers2 = [10, 20, 30]
combined = zip_longest(numbers1, numbers2, fillvalue=0)
# Print the combined lists
for item in combined:
print(item)

--

--

Prasad
Prasad

Written by Prasad

I am a OpenSource Enthusiast|Python Lover who attempts to find simple explanations for questions and share them with others

No responses yet