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.

1 Answer 1

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)]
Sign up to request clarification or add additional context in comments.

3 Comments

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.
I just was playing with itertools, and figured out, that itertools.combinations() would produce duplicates if your list contains some. See here for detail So maybe you also should wrap it with a set ;-)
@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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.