开发者

Python removing items from list [duplicate]

开发者 https://www.devze.com 2023-03-17 13:18 出处:网络
This question already has answers here: 开发者_开发技巧 Strange result when removing item from a list while iterating over it
This question already has answers here: 开发者_开发技巧 Strange result when removing item from a list while iterating over it (8 answers) Closed 7 years ago.

I have a list in the given format:

[['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]

There are some elements like this in the list ['Linus Torvalds', ''] and I want to remove those. So why doesn't the following code remove them?

for i in people:
    if(i[0] == '' or i[1] == ''):
        print people.pop(people.index(i))


You are changing the list while iterating over it and this is the source of your problems. An approach that works is

people[:] = [p for p in people if p[0] != '' and p[1] != '']

this way a new temporary list containing only the elements you want is built and then assigned to the original list object when the operation is complete.


Or even people[:] = [p for p in people if all(p)] if you want to resize the list "in place".


You're modifying the list's length while iterating over it. That causes you to skip values. When you pop one item off the list, here's what happens (stealing from this answer):

[1, 2, 3, 4, 5, 6...]
 ^

That's the state of the list initially; now say 1 is removed and the loop goes to the second item in the list:

[2, 3, 4, 5, 6...]
    ^

And so on.


It's a bad idea to remove things from a list as you iterate over it. So, try one of these instead (Also, I think your condition is not what you want it to be - I've fixed it):

L = [['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]
delete_these = []
for index, i in enumerate(L):
    if not i[-1].strip():
        delete_these.append(i)
for i in delete_these:
    L.pop(i)
    delete_these = map(lambda x: x-1, delete_these)

OR

L = [i for i in L if i[-1].strip()]

OR

answer = []
for i in L:
    if i[-1].strip():
        answer.append(i)

OR

i = 0
while i < len(L):
    if not L[i][-1].strip():
        L.pop(i)
    else:
        i += 1

Hope this helps

0

精彩评论

暂无评论...
验证码 换一张
取 消