Kaizer von Maanen
Kaizer von Maanen

Reputation: 987

Python: How do i use itertools?

I am trying to make a list containing all possible variations of 1 and 0. like for example if I have just two digits I want a list like this:

[[0,0], [0,1], [1,0], [1,1]]

But if I decide to have 3 digits I want to have a list like this:

[[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1,1]]

Someone told me to use itertools, but I cannot get it to work the way I want.

>>> list(itertools.permutations((range(2))))
[(0, 1), (1, 0)]
>>> [list(itertools.product((range(2))))]
[[(0,), (1,)]]

Is there a way to do this? And question number two, how would i find documentation on modules like this? I am just flailing blindly here

Upvotes: 5

Views: 9534

Answers (3)

falsetru
falsetru

Reputation: 369124

itertools.product(.., repeat=n)

>>> import itertools
>>> list(itertools.product((0,1), repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

Python Module Index contains links for standard library modules documentation.

Upvotes: 9

TerryA
TerryA

Reputation: 59974

itertools.product() can take a second argument: the length. It defaults to one, as you have seen. Simply, you can add repeat=n to your function call:

>>> list(itertools.product(range(2), repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

To find the docs, you can either use help(itertools) or just do a quick google (or whatever your search engine is) search "itertools python".

Upvotes: 6

Steve Barnes
Steve Barnes

Reputation: 28390

How to find some information on itertools, (other than here or google), or just about anything python:

python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] o
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> help(itertools)
Help on built-in module itertools:

NAME
    itertools - Functional tools for creating and using iterators.

FILE
    (built-in)

DESCRIPTION
    Infinite iterators:
    count([n]) --> n, n+1, n+2, ...
    cycle(p) --> p0, p1, ... plast, p0, p1, ...
    repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times

    Iterators terminating on the shortest input sequence:
    izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ...
    izip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ...
    ifilter(pred, seq) --> elements of seq where pred(elem) is True
    ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False
    islice(seq, [start,] stop [, step]) --> elements from
           seq[start:stop:step]
    imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ...
    starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...
    tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n
-- More  --

Upvotes: 6

Related Questions