0

While writing some code I notice something strange, if you take this code:

data = ['a','b','c','d','e']
print("start", len(data))
while(len(data) > 0):
  print("while", len(data))
  for i in data:
    print("for", i)
    del data[data.index(i)]
print("end", len(data))

If I execute it, it returns:

('start', 5)
('while', 5)
('for', 'a')
('for', 'c')
('for', 'e')
('while', 2)
('for', 'b')
('while', 1)
('for', 'd')
('end', 0)

This is not what I expected to happen, this is what i thought would happen:

('start', 5)
('while', 5)
('for', 'a')
('for', 'b')
('for', 'c')
('for', 'd')
('for', 'e')
('end', 0)

It's both running the list out of order (which is annoying but that wholly unexpected) and running more than one while loop. As I said in the brackets then list returning out of order is not really the problem its the multiple while loops cycles that confused me. Can someone explain why this is happening? A solution would be pleasant too.

Here is a link to the demo code on trinket.io: https://trinket.io/python/46f433793d

Jongware
  • 22,200
  • 8
  • 54
  • 100
Duncan
  • 1
  • 1

0 Answers0