简体   繁体   中英

Removing elements from a List in Python

I'm using python 3.4 and just learning the basics, so please bear with me..

listA = [1,2]
for a in listA:
    listA.remove(a)
print(listA)

What is suppose is I get an empty list, but what I get is a list with value '2'. I debugged the code with large no. of values in list and when the list is having a single element the for loop exit. Why is the last element not removed from the list..?

You should not change a list while iterating over it. The indices of the list change as you remove items, so that some items are never evaluated. Use a list comprehension instead, which creates a new list:

[a for a in list if ...]

In other words, try something like this:

>>> A = [1, 2, 3, 4]
>>> A = [a for a in A if a < 4]       # creates new list and evaluates each element of old
>>> A
[1, 2, 3]

When you use a for-loop, an internal counter is used. If you shift the remaining elements to the left while iterating over the list , the left-most element in the remaining list will be not be evaluated. See the note for the for statement .

That happens because the length of the for is evaluated only at the beginning and you modify the list while looping on it:

>>> l = [1,2,3]
>>> l
[1, 2, 3]
>>> for a in l:
    print(a)
    print(l)
    l.remove(a)
    print(a)
    print(l)
    print("---")


1
[1, 2, 3]
1
[2, 3]
---
3
[2, 3]
3
[2]
---
>>>

See? The value of the implicit variable used to index the list and loop over it increases and skip the second element.

If you want to empty a list, do a clear:

>>> l.clear()
>>> l
[]

Or use a different way of looping over the list, if you need to modify it while looping over it.

As mentioned by @Justin in comments, do not alter the list while iterating on it. As you keep on removing the elements from the list, the size of the list shrinks, which will change the indices of the element.

If you need to remove elements from the list one-by-one, iterate over a copy of the list leaving the original list intact, while modifying the duplicated list in the process.

>>> listA = [1,2,3,4]
>>> listB = [1,2,3,4]

>>> for each in listA:
...     print each
...     listB.remove(each)
1
2
3
4
>>> listB
[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM