Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid duplicates in nested loop python

Tags:

python

arrays

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!

like image 723
Nick Pietrushka Avatar asked Sep 05 '25 04:09

Nick Pietrushka


1 Answers

for k, x in enumerate(string_list):
    for y in string_list[k:]:
        print(x,y)
like image 101
Daniel Walker Avatar answered Sep 07 '25 21:09

Daniel Walker