Python itertools Module



The itertools module in Python provides a collection of tools for handling iterators efficiently. It includes several functions that allow for fast and memory-efficient looping, such as count(), cycle(), and repeat().

Additionally, it offers combinatorial functions like product(), permutations(), and combinations(), which are useful for generating various combinations or arrangements of data. This makes the itertools module powerful for tasks that involve complex iteration.

Infinite Iterators

S.No Function & Description
1

count()

Returns an iterator that generates consecutive integers, starting from a given number.

2

cycle()

Returns an iterator that cycles through an iterable indefinitely.

3

repeat()

Returns an iterator that repeats a given element indefinitely or up to a specified number of times.

Iterators Terminating on the Shortest Input Sequence

These functions return iterators that stop when the shortest input sequence is exhausted.

S.No Module & Description
1

accumulate()

Returns an iterator with accumulated sums or other binary functions.

2

batched()

Returns an iterator that yields consecutive chunks of data.

3

chain()

Returns an iterator that links multiple iterables sequentially.

4

compress()

Filters elements in an iterable based on a selector iterable.

5

dropwhile()

Skips elements in an iterable while a condition is true and then returns the remaining elements.

6

filterfalse()

Returns elements from an iterable for which the function returns false.

7

groupby()

Groups adjacent elements in an iterable based on a key function.

8

islice()

Returns selected elements from an iterable.

9

pairwise()

Returns consecutive pairs of elements from an iterable.

10

starmap()

Applies a function to arguments taken in tuples from an iterable.

11

takewhile()

Returns elements from an iterable while a condition is true.

12

tee()

Returns multiple independent iterators from a single iterable.

13

zip_longest()

Returns tuples containing elements from multiple iterables, filling missing values with a specified default.

Combinatoric Iterators

These functions provide combinatorial operations like permutations, combinations, and Cartesian products.

S.No Module & Description
1

product()

Computes the Cartesian product of input iterables.

2

permutations()

Returns successive permutations of elements in the iterable.

3

combinations()

Returns successive combinations of elements from the iterable.

4

combinations_with_replacement()

Returns combinations with replacement, allowing repeated elements in each combination.

python_modules.htm
Advertisements