0

I did

    a = range(17,30)
    print(a)
    for i, item in enumerate(a):
        if (item%3)==0:
            print("del {0}:{1}".format(i, item))
            del a[i]
    print(a)

Then I got,

[17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
del 1:18
del 3:21
del 5:24
del 7:27

The answer is correct but I suppose the index of deleted item should be 1, 4, 7, 10

newBike
  • 14,385
  • 29
  • 109
  • 192

1 Answers1

1

What happens is that you are deleting the items of the list a, so the indices changes. You can easily see this if you print the list a inside the loop:

a = range(17, 30)

for i, item in enumerate(a):
    if (item % 3) == 0:
        print(a)
        print("del  {0}:{1}".format(i, item))
        del a[i]

Output:

  0   1   2   3   4   5   6   7   8   9  10  11  12
-----------------------------------------------------
[17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
del  1:18
[17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
del  3:21
[17, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29]
del  5:24
[17, 19, 20, 22, 23, 25, 26, 27, 28, 29]
del  7:27
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73