+3 votes
in Programming Languages by (8.2k points)
I have a list e.g. [1,2,3,4]. Is there any Python module that can be helpful in finding the power set of the list?

1 Answer

+1 vote
by (11.2k points)

You can use module itertools to get the power set of a list or set. Have a look at the following example.

>>> from itertools import *
>>> a=[1,2,3,4]
>>> chain.from_iterable(combinations(a,r) for r in range(len(a)+1))
<itertools.chain object at 0x7f9b364c63c8>
>>> t=chain.from_iterable(combinations(a,r) for r in range(len(a)+1))
>>> print(t)
<itertools.chain object at 0x7f9b364d6080>
>>> t=[e for e in chain.from_iterable(combinations(a,r) for r in range(len(a)+1))]
>>> t
[(), (1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (1, 2, 3, 4)]
>>> len(t)
16
 

...