-2

I'm using for loop which should run to the number of items in the given list. instead for some reason it is skipping every adjacent element.

snakes = [50, 23, 45, 67, 82]
ran = 0
for x, snake in enumerate (snakes):
    z = 0
    print("ran : ", ran)
    ran +=1
    while snake in snakes:
        z += 1
        if z == snake:
            print(x, snake)
            snakes.pop(x)

output

ran :  0
0 50
ran :  1
1 45
ran :  2
2 82
toaster
  • 21
  • 3
  • you are deleteing the elements from the list you are iterating – deadshot May 08 '20 at 20:14
  • yes 50 is deleted then it should go for the next element 23? how is it skipping 23? is it because it is looking for the second element in the list and since 50 has been removed so 23 is no longer the 2nd element, right? – toaster May 08 '20 at 20:18
  • if you delete some element from list indices of rest of the the elements changes – deadshot May 08 '20 at 20:19

1 Answers1

1

In your for loop, (x, snake) count up, 0 1 2 3 4 until the end of the list snakes which looks like:

0  1  2  3  4
50 23 45 67 82

On the first loop (0, 50), you pop 50 from snakes which now looks like:

0  1  2  3
23 45 67 82

Your for loop has finished the first loop, and moves on to element 1, which is now 45.