Remove Multiple Items from a Python List
TL;DR
Use del
to nuke multiple items from a Python list.
=
del
['alfa', 'delta']
Details
del
deleted items from a list without making a new one1. It works by passing it a list with optional sequences.
The docs for sequences2 say:
Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j.
and
Some sequences also support “extended slicing” with a third “step” parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i <= x < j.
Frankly, I can't follow that. I just throw numbers at the code until I see what I'm looking for.
Show Me The Codes
Here's a few examples to show the possibilites in action:
Run To The End
=
del
['alfa', 'bravo', 'charlie', 'delta']
Yoink Until
=
del
['echo', 'foxtrot', 'golf', 'hotel']
Split the Middle
=
del
['alfa', 'bravo', 'golf', 'hotel']
Hopscotch
=
del
['bravo', 'delta', 'foxtrot', 'hotel']
Thought Required
I can know what's going to happen with the sequences in advance if I really stop and think about it. Like, there's explicit math behind it. It's just counter-intuitive to me.
Poking at things until they do what I want is faster and works just fine.
-a
Endnotes
Check out Remove The First (or Any) Item from a Python List if you only need to remove a single item (and optionally capture it).
References
Footnotes
Slicing can be used to keep the original list in place (e.g. =
).