# Itertools Module

## Syntax

• `import itertools`

## Chaining multiple iterators together

Use `itertools.chain` to create a single generator which will yield the values from several generators in sequence.

Results in:

As an alternate constructor, you can use the classmethod `chain.from_iterable` which takes as its single parameter an iterable of iterables. To get the same result as above:

While `chain` can take an arbitrary number of arguments, `chain.from_iterable` is the only way to chain an infinite number of iterables.

## Combinations method in Itertools Module

`itertools.combinations` will return a generator of the k-combination sequence of a list.

In other words: It will return a generator of tuples of all the possible k-wise combinations of the input list.

For Example:

If you have a list:

Output:

`[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]`

The above output is a generator converted to a list of tuples of all the possible pair-wise combinations of the input list `a`

You can also find all the 3-combinations:

Output:

## Cycle through elements in an iterator

`cycle` is an infinite iterator.

Therefore, take care to give boundaries when using this to avoid an infinite loop. Example:

## Get an accumulated sum of numbers in an iterable

Python 3.x3.2

`accumulate` yields a cumulative sum (or product) of numbers.

## Grouping items from an iterable object using a function

Generate the grouped generator, grouping by the second element in each tuple:

Only groups of consecutive elements are grouped. You may need to sort by the same key before calling groupby For E.g, (Last element is changed)

The group returned by groupby is an iterator that will be invalid before next iteration. E.g the following will not work if you want the groups to be sorted by key. Group 5 is empty below because when group 2 is fetched it invalidates 5

To correctly do sorting, create a list from the iterator before sorting

## itertools.count

Introduction:

This simple function generates infinite series of numbers. For example...

Note that we must break or it prints forever!

Output:

Arguments:

`count()` takes two arguments, `start` and `step`:

Output:

## itertools.dropwhile

itertools.dropwhile enables you to take items from a sequence after a condition first becomes `False`.

This outputs `[13, 14, 22, 23, 44]`.

(This example is same as the example for `takewhile` but using `dropwhile`.)

Note that, the first number that violates the predicate (i.e.: the function returning a Boolean value) `is_even` is, `13`. All the elements before that, are discarded.

The output produced by `dropwhile` is similar to the output generated from the code below.

The concatenation of results produced by `takewhile` and `dropwhile` produces the original iterable.

`result = list(itertools.takewhile(is_even, lst)) + list(itertools.dropwhile(is_even, lst))`

## itertools.permutations

`itertools.permutations` returns a generator with successive r-length permutations of elements in the iterable.

if the list `a` has duplicate elements, the resulting permutations will have duplicate elements, you can use `set` to get unique permutations:

## itertools.product

This function lets you iterate over the Cartesian product of a list of iterables.

For example,

is equivalent to

Like all python functions that accept a variable number of arguments, we can pass a list to itertools.product for unpacking, with the * operator.

Thus,

produces the same results as both of the previous examples.

## itertools.repeat

Repeat something n times:

## itertools.takewhile

itertools.takewhile enables you to take items from a sequence until a condition first becomes `False`.

This outputs `[0, 2, 4, 12, 18]`.

Note that, the first number that violates the predicate (i.e.: the function returning a Boolean value) `is_even` is, `13`. Once `takewhile` encounters a value that produces `False` for the given predicate, it breaks out.

The output produced by `takewhile` is similar to the output generated from the code below.

Note: The concatenation of results produced by `takewhile` and `dropwhile` produces the original iterable.

`result = list(itertools.takewhile(is_even, lst)) + list(itertools.dropwhile(is_even, lst))`

## Take a slice of a generator

Itertools "islice" allows you to slice a generator:

Normally you cannot slice a generator:

Will give

However, this works:

Note that like a regular slice, you can also use `start`, `stop` and `step` arguments:

## Zipping two iterators until they are both exhausted

Similar to the built-in function `zip()`, `itertools.zip_longest` will continue iterating beyond the end of the shorter of two iterables.

An optional `fillvalue` argument can be passed (defaults to `''`) like so:

In Python 2.6 and 2.7, this function is called `itertools.izip_longest`.