'Avoid duplicates in nested loop python

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!



Solution 1:[1]

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

Solution 2:[2]

You can use itertools.combinations:

for x, y in it.combinations(string_list, 2):
    # process x, y

Solution 3:[3]

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
}]

Solution 4:[4]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Walker
Solution 2 a_guest
Solution 3
Solution 4 John Gordon