Actually I was working with this code:
m=[0,1,2,3,4,5,6,7]
for i in m:
m.remove(i)
print(m)
This looks pretty simple.
for i in m:
print(i)
will print every elements in the list m. So the for part in our code will extract every elements of the list and remove it one by one. So the output that I except is [].
But I got [1,3,5,7].
How it can be the output and where I was wrong?
CodePudding user response:
What happens here is, you're removing items in the list on the go.
Eg,
On the first remove() call, it removes 0 from the list (current index is 0).
On the second remove() call, the current index is 1, but the list contains [1,2,3,...]. Now the the index 1 contains "2" instead of "1". Because 0 has been removed and the size of list is just changed.
So to clear list in python, you can use,
m.clear()
CodePudding user response:
If you know how to use a debugger, that would be the ideal way to diagnose this, but otherwise, try running this code to see what's going on:
x = [0, 1, 2, 3, 4, 5, 6, 7]
for i in x.copy():
x.remove(i)
print(x)
print(x)
m = [0, 1, 2, 3, 4, 5, 6, 7]
for i in m:
m.remove(i)
print(m)
print(m)
During a given execution, the for loop accesses an element and then deletes it. For example, it first deletes the element at index 0, with value 0, leaving you with [1, 2, 3, 4, 5, 6, 7]
. Then it moves on to the element at index 1, value 2, and deletes that, leaving you with [1, 3, 4, 5, 6, 7]
.
In general, avoid messing around with a list in Python. If you have to delete all elements, use m.clear()
. If you have to delete some elements or do some other stuff, prefer to use list comprehension to create a new object.