Try this?
Fruits = ['apple','hello','banana','lichi','mango']
while Fruits:
print(Fruits.pop())
In your code sample, you can imagine that in the first loop, when 'apple'
was removed from the list. the Fruits was changed to ['hello','banana','lichi','mango']
. So, in the second loop, 'banana'
was extracted and removed as the second item and 'hello'
was bypassed. So, you know, avoid changing size of the list in for
loop.
updated according to request:
Fruits = ['apple','hello','banana','lichi','mango']
i = 0
while i < len(Fruits):
item = Fruits[i]
print(item)
if item == 'apple':
Fruits.remove(item)
else:
i += 1
The for
loop in Python does not like C/C++. It is actually transferred to go through the iterator. It is hard to be controlled precisely. So, while
clause is used here. But while
clause should be avoided because it is easy to cause dead loop.