rickri
rickri

Reputation: 43

Iterate over same list twice and avoid duplicates in python

I have a list [1,2,3,4,5] which I iterate over twice with for loops.

for i in list:
    for j in list:
        print(i,j)

I do not care about the order of i and j and therefore I receive a lot of duplicates. For example 1,2 and 2,1 are the "same" for me. Same thing for 1,4 and 4,1 and 3,5 and 5,3 and so on.

I would like to remove these duplicates but do not really understand how I should go about doing so.

Upvotes: 2

Views: 5568

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

Actually you want the combinations :

>>> list(combinations( [1,2,3,4,5],2))
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

And as the result of itertools.combinations is a generator if you want to loop over it you don't need list :

for i,j in combinations( [1,2,3,4,5],2):
      #do stuff

Also as mentioned in comments you can use itertools.combinations_with_replacement if you would like to have tuples like (n, n) :

>>> list(combinations_with_replacement([1, 2, 3, 4, 5],2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5), (5, 5)]

Upvotes: 8

Related Questions