Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple items from list in Python [closed]

Tags:

python

list

So, for example, I got a list: myList=["asdf","ghjk","qwer","tyui"]
I also have a list of index numbers of the items I want to remove: removeIndexList=[1,3] (I want to remove items 1 and 3 from the list above)

What would be the best way to do this?

like image 581
mid_kid Avatar asked Sep 16 '13 21:09

mid_kid


2 Answers

Use a list comprehension with enumerate():

newlist = [v for i, v in enumerate(oldlist) if i not in removelist]

making removelist a set instead will help speed things along:

removeset = set(removelist)
newlist = [v for i, v in enumerate(oldlist) if i not in removeset]

Demo:

>>> oldlist = ["asdf", "ghjk", "qwer", "tyui"]
>>> removeset = set([1, 3])
>>> [v for i, v in enumerate(oldlist) if i not in removeset]
['asdf', 'qwer']
like image 148
Martijn Pieters Avatar answered Sep 18 '22 09:09

Martijn Pieters


The obvious way will not work:

list=["asdf","ghjk","qwer","tyui"]
removelist=[1,3] 
for index in removelist:
    del list[index]

The problem is that after you've deleted #1, "ghjk", everything after that gets shifted forward. So #3 is no longer "tyui", it's past the end of the list.


You can solve this by making sure you walk backward:

list=["asdf","ghjk","qwer","tyui"]
removelist=[1,3] 
for index in sorted(removelist, reverse=True):
    del list[index]

However, it's generally better to just build a new filtered list instead, as suggested by Martijn Pieters:

list = [v for i, v in enumerate(list) if i not in removelist]
like image 36
abarnert Avatar answered Sep 22 '22 09:09

abarnert