home ~ projects ~ socials

Remove Multiple Items from a Python List

TL;DR

Use del to nuke multiple items from a Python list.

items = [
  "alfa", "bravo", "charlie", "delta"
]

del items[1:3]

print(items)
Output:
['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

items = [
  "alfa", "bravo", "charlie", "delta",
  "echo", "foxtrot", "golf", "hotel"
]

del items[4:]

print(items)
Output:
['alfa', 'bravo', 'charlie', 'delta']

Yoink Until

items = [
  "alfa", "bravo", "charlie", "delta",
  "echo", "foxtrot", "golf", "hotel"
]

del items[:4]

print(items)
Output:
['echo', 'foxtrot', 'golf', 'hotel']

Split the Middle

items = [
  "alfa", "bravo", "charlie", "delta",
  "echo", "foxtrot", "golf", "hotel"
]

del items[2:6]

print(items)
Output:
['alfa', 'bravo', 'golf', 'hotel']

Hopscotch

items = [
  "alfa", "bravo", "charlie", "delta",
  "echo", "foxtrot", "golf", "hotel"
]

del items[::2]

print(items)
Output:
['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

-- end of line --

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. new_list = items[1:]).