-1

I want to check every number with every number in a list without repeating any checks. This code:

a = [0,1,2,3,4]
b = a

for i in a :
    for j in b:
        print(i,j)
    del b[0]

It gives the output:

0 0
0 1
0 2
0 3
0 4
2 1
2 2
2 3
2 4
4 2
4 3
4 4

The output I want is:

0 0
0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4

Why does i skip 1 and 3? It is fixed when I remove the line 'del b[0]' but to my understanding, this line should not have any impact on the value of 'i'

hjjinx
  • 55
  • 6
  • 2
    You are modifying the list you are iterating over: don't do that! – Reblochon Masque Jul 20 '18 at 08:24
  • What can I do here then to achieve the desired output? – hjjinx Jul 20 '18 at 08:25
  • see the linked dupe – Reblochon Masque Jul 20 '18 at 08:26
  • And most importantly why is 1 and 3 skipped? It is really weird for me to see that as I am not doing anything to list a and still it is being modified or some of the numbers are skipped. – hjjinx Jul 20 '18 at 08:27
  • Deleting the element out of `b` doesn't have an impact on the value of `i`. But it does change the *meaning* of `i` because after the delete, `b[i]` doesn't point to the same element anymore. And `a` and `b` are both pointing to the same list, so deleting from `b` also deletes from `a`. – BoarGules Jul 20 '18 at 08:29
  • That I didn't knew that they were both the same list. blhsing explained nicely in his answer. Thanks for your time. – hjjinx Jul 20 '18 at 08:33

2 Answers2

1

b is assigned with reference to a, not a copy of list a, so when you delete item 0 from b, it is also deleted from a. Instead, you should assign to b a copy of a:

a = [0,1,2,3,4]
b = a[:]

for i in a:
    for j in b:
        print(i,j)
    del b[0]

This outputs:

0 0
0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    Yes!! This is what I was looking for. I understand now that it was a reference of a. Thanks! – hjjinx Jul 20 '18 at 08:31
  • Glad to be of help. Can you mark this answer as accepted if you think it is correct? – blhsing Jul 20 '18 at 08:33
  • 1
    I tried that but it will only be accepted after 5 minutes of writing. I will do that after 2 minutes – hjjinx Jul 20 '18 at 08:35
0

You are modifying the list you are iterating on, it is obvious that the length change dynamically.

Iterate the list with a counter, and decrease the counter when you delete something in order to not "jump" elements.

Please note that b is a reference of a.

Andrea Perelli
  • 156
  • 2
  • 3
  • 14