-1

Lets take a list,

nums = [-2,1,-3,4,-1,2,1,-5,4]

Now when you run: for e in nums: print(e) you get all the elements printed in order:

-2
1
-3
4
-1
2
1
-5
4

Now the weird part is when I try to remove these elements in order:

for e in nums:
    print(f"before: {nums}, next {e} will be removed..")
    nums.remove(e)
    print(f"after: {nums}")

The result:

before: [-2, 1, -3, 4, -1, 2, 1, -5, 4], next -2 will be removed..
after: [1, -3, 4, -1, 2, 1, -5, 4]
before: [1, -3, 4, -1, 2, 1, -5, 4], next -3 will be removed..
after: [1, 4, -1, 2, 1, -5, 4]
before: [1, 4, -1, 2, 1, -5, 4], next -1 will be removed..
after: [1, 4, 2, 1, -5, 4]
before: [1, 4, 2, 1, -5, 4], next 1 will be removed..
after: [4, 2, 1, -5, 4]
before: [4, 2, 1, -5, 4], next 4 will be removed..
after: [2, 1, -5, 4]

Now what just happened?

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
Ani Menon
  • 27,209
  • 16
  • 105
  • 126
  • `for e in nums[:]:`... – Nick Oct 08 '22 at 06:40
  • Your code says `'NoneType' object has no attribute 'remove'` on line `nums = nums.remove(e)`, as expected (`nums.remove(e)` returns `None`). Python 3.6 – Dmitry Oct 08 '22 at 06:41
  • @Nick That answered it, somehow hadn't seen it when I searched. Thanks. Also marked my own question duplicate for the first time :D – Ani Menon Oct 08 '22 at 19:45

1 Answers1

0

the problem here is that you're modifying the list as you are iterating over it.

As you're doing it now, you're iterating over the list and your initial index (0) is set to -2, once you remove that, the next index (1) will point to -3 instead of 1, you remove, -3, and you'll never reach 1, and this will be the same for all even indicies of the original list, as you're only ever reaching the odd indicies by doing this.

As nick said, use for e in nums[:]: as it copies the list before iterating, or you can use for e in nums.copy():

Hope this helps :)

ByteTh1ef
  • 71
  • 5
  • I got it from Nick's comment, but the explanation here isn't right. It isn't reaching only odd indicies. In the example first `-2` gets removed which is index 0, next `-3` (at index 1) gets removed instead of `1`.. so on.. After 3 iterations, `1` gets removed which is now at index 0! – Ani Menon Oct 08 '22 at 19:55
  • You’re right I didn’t mean to say only odd, I wrote this response late at night so I messed up my comment, will update later, glad you got it though :D – ByteTh1ef Oct 08 '22 at 22:21