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?
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']
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With