Avoid duplicates in nested loop python

Viewed 2281

So i have nested loops and array [[0, 1], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4]]:

for x in string_list:
        for y in string_list:
            print(x,y)

provides me the output

[0, 1] [0, 1]
[0, 1] [0, 1, 2, 3, 4, 5, 6]
[0, 1] [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5, 6] [0, 1]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4] [0, 1]
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]

But i have a lot of duplicates pairs and i did:

for x in range(0, len(string_list)):
      for y in range(x+1, len(string_list)): 
          print(x,y, string_list)

but it's working only for 2 digit pairs. So what i want is:

[0, 1] [0, 1]
[0, 1] [0, 1, 2, 3, 4, 5, 6] 
[0, 1] [0, 1, 2, 3, 4]
**[0, 1, 2, 3, 4, 5, 6] [0, 1]** // avoid to output that pair cause we had that one 
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4] [0, 1]
**[0, 1, 2, 3, 4] [0, 1, 2, 3, 4, 5, 6]** // avoid to output that pair cause we had that one 
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]

does it possible to do without using itertools ? Thank you!

4 Answers
for k, x in enumerate(string_list):
    for y in string_list[k:]:
        print(x,y)

Obviously using itertools.combinations is ideal, but since you said you don't want to use itertools, you could use a set comprehension to build the set of unique combinations (you have to convert the lists to tuples to make them hashable), then convert them back to lists as needed:

[list(list(t) for t in f) for f in {
    frozenset((tuple(x), tuple(y))) for y in string_list for x in string_list
}]

You can put a continue statement in the inner loop to skip duplicates:

 for x in string_list:
     for y in string_list:
         if x == y:
             continue
         print(x,y)
Related