Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python removing items from list [duplicate]

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))
like image 615
Diego Allen Avatar asked Dec 03 '22 02:12

Diego Allen


2 Answers

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.

like image 167
6502 Avatar answered Dec 08 '22 00:12

6502


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

like image 28
Matt Joiner Avatar answered Dec 08 '22 00:12

Matt Joiner