Lately I learned about lists and for loops, as well as the command .pop() that indicates and removes the last item in a list.
So I tried to write a code to remove the last items in a list one by one, until it remains with only one item.
The code is:
list_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
for i in list_A:
print(list_A.pop())
if 'c' not in list_A:
break
print("job done.")
The output of python 3.6 gives me this:
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
j
i
h
g
f
job done.
As you can see, it actually worked, but for a half of it?
I was expecting:
j
i
h
g
f
e
d
c
job done
I mean, I will be more comfortable if it returns some error, that means the code is not right. But why did it work, but not a full way through?
解决方案
You are mutating the list whilst iterating over it.
You can use a while loop to do this:
list_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
while 'c' in list_A:
print(list_A.pop())
print('job done')
Output:
j
i
h
g
f
e
d
c
job done
A more efficient way would be to determine the index of the first instance of the sentinel character, and remove it and the rest of the list (although the characters are not printed as they are removed):
try:
pos = list_A.index('c')
list_A[:] = list_A[:pos]
# del list_A[pos:] # more efficient alternative suggested by @ShadowRanger
except ValueError as e:
pass