Skip to content Skip to sidebar Skip to footer

Python Removing Items From List

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

Solution 1:

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.

Solution 2:

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

Solution 3:

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.

Solution 4:

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 inenumerate(L):
    ifnot 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 = 0while i < len(L):
    ifnot L[i][-1].strip():
        L.pop(i)
    else:
        i += 1

Hope this helps

Post a Comment for "Python Removing Items From List"