Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate through combinations of a list [duplicate]

I have a list of elements, say

list = [1, 2, 3, 4]

and I would like to iterate through couples of distinct elements of this list, so

for x, y in some_iterator(list):
    print x, y

should show

1 2
1 3
1 4
2 3
2 4
3 4

Note that I don't want all combinations of list as in this question. Just the combinations of a given length.

What would be the most pythonic way of doing this ?


What if I wanted to do the same with n-uples ? For instance with combinations of 3 elements out of n

for x, y, z in another_iterator(list):
    print x, y, z

would show

1 2 3
1 2 4
2 3 4
like image 358
usernumber Avatar asked Jan 16 '17 16:01

usernumber


People also ask

How do you get all the unique combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

Can I modify list while iterating?

The general rule of thumb is that you don't modify a collection/array/list while iterating over it. Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.


1 Answers

Use itertools.combinations:

from itertools import combinations

for combo in combinations(lst, 2):  # 2 for pairs, 3 for triplets, etc
    print(combo)
like image 97
user2390182 Avatar answered Oct 10 '22 20:10

user2390182