Skip to content Skip to sidebar Skip to footer

How To Generate List Combinations?

I want to produce a list of lists that represents all possible combinations of the numbers 0 and 1. The lists have length n. The output should look like this. For n=1: [ [0], [1] ]

Solution 1:

You're looking for itertools.product(...).

>>>from itertools import product>>>list(product([1, 0], repeat=2))
[(1, 1), (1, 0), (0, 1), (0, 0)]

If you want to convert the inner elements to list type, use a list comprehension

>>> [list(elem) for elem in product([1, 0], repeat =2)]
[[1, 1], [1, 0], [0, 1], [0, 0]]

Or by using map()

>>> map(list, product([1, 0], repeat=2))
[[1, 1], [1, 0], [0, 1], [0, 0]]

Solution 2:

Use itertools.product, assigning the repeat to n.

from itertools import product
list(product([0,1], repeat=n))

Demo:

>>> list(product([0,1], repeat=2))
[(0, 0), (0, 1), (1, 0), (1, 1)]
>>> list(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)]

Solution 3:

>>>from itertools import product>>>list(product([0, 1], repeat=2))
[(0, 0), (0, 1), (1, 0), (1, 1)]
>>>>>>list(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)]

To get list of list, you can do:

>>> map(list, list(product([0, 1], repeat=2)))
[[0, 0], [0, 1], [1, 0], [1, 1]]

Solution 4:

Just to add a bit of diversity, here's another way of achieving this:

>>> [map(int, format(i, "03b")) for i in range(8)][[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

Post a Comment for "How To Generate List Combinations?"