2

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.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
rickri
  • 43
  • 2
  • 9

1 Answers1

8

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)]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    Maybee you also want to use `itertools.combinations_with_replacement([1, 2, 3, 4, 5],2)` if you would like to have tuples like `(n, n)` included. – Finn Feb 17 '15 at 19:24
  • 1
    I just was playing with itertools, and figured out, that `itertools.combinations()` would produce duplicates if your list contains some. [See here for detail](http://stackoverflow.com/questions/6534430/why-does-pythons-itertools-permutations-contain-duplicates-when-the-original) So maybe you also should wrap it with a set ;-) – Finn Feb 17 '15 at 20:02
  • @Finn Yes if the main list contain the dups the result would be contain duplicated result! but in this case as the main list doesn't contain dups there is no need to use `set`! – Mazdak Feb 17 '15 at 22:17