Jan 18, 2012

Python Standard Library: Itertools

chain

Return a chain object whose .next() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted.
[x for x in chain([1, 2],[3, 4])]
# [1, 2, 3, 4]

izip

Works like the zip() function but consumes less memory by returning an iterator instead of a list.
[x for x in izip([1, 2],[3, 4])]
# [(1, 3), (2, 4)]

[x for x in izip([1, 2, 4],[3, 4])]
# [(1, 3), (2, 4)]

islice

Works like the slice() function but consumes less memory by returning an iterator instead of a list.
[x for x in islice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4)] # first n-elements
# [0, 1, 2, 3]

[x for x in islice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 2, 5)]
# [2, 3, 4]

[x for x in islice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 0, 10, 3)]
# [0, 3, 6, 9]

#same with count()
from itertools import islice, count
[x for x in islice(count(), 0, 10, 3)]
# [0, 3, 6, 9]

imap

Like map() except that it returns an iterator instead of a list and that it stops when the shortest iterable is exhausted instead of filling in None for shorter iterables.
[x for x in imap(lambda x: 2*x, [1,2,3])]
# [2, 4, 6]

combination

Return successive r-length combinations of elements in the iterable.
[x for x in combinations([1, 2, 3], 1)]
# [(1,), (2,), (3,)]

[x for x in combinations([1, 2, 3], 2)]
# [(1, 2), (1, 3), (2, 3)]

[x for x in combinations([1, 2, 3], 3)]
# [(1, 2, 3)]

[x for x in combinations([1, 2, 3], 4)]
# []

cycle

Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely.
for x in cycle(['one', 'two', 'three']):
    print x
  
one
two
three
one
two
three
one
two
......

repeat

Create an iterator which returns the element for the specified number of times. If not specified, returns the element endlessly.
for x in repeat(['one', 'two', 'three'], 2):
    print x
['one', 'two', 'three']
['one', 'two', 'three']
Much faster then
for x in ['one', 'two', 'three'] * 2:
    print x

No comments: