Combinations method in Itertools Module

suggest change

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:

a = [1,2,3,4,5]
b = list(itertools.combinations(a, 2))
print b

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:

a = [1,2,3,4,5]
b = list(itertools.combinations(a, 3))
print b

Output:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents