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
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.
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.
Use itertools.combinations
:
from itertools import combinations
for combo in combinations(lst, 2): # 2 for pairs, 3 for triplets, etc
print(combo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With