home ~ projects ~ socials

Remove The First (or Any) Item from a Python List

TL;DR

I use .pop(0) to yoink the first item out of python lists.

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

items.pop(0)

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

Details

Pulling First Place

.pop() returns the value it removes. You can capture it in a variable.

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

former_first = items.pop(0)

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

Looking Later

.pop(0) deals with the first element. Changing the number changes the element. The number is zero indexed. So, doing .pop(2) pulls the third element.

items = ["alfa", "bravo", "charlie", "delta"]
former_third = items.pop(2)

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

Same, Same

.pop(#) operates directly on the list. Changes are made in place without creating a new one1.

The Little Differences

My first language was Perl. Its version of.pop() only pulls stuff from the end of arrays. As much as I've worked with Python, I sometimes forget its .pop() is way more versatile.

-a

-- end of line --

Endnotes

Python's del() can be used to remove elements as well. And, not just one at a time. It uses range syntax. It doesn't return items, though.

More details about it at: Remove Multiple Items from a Python List

References

Footnotes

Slicing can be used to keep the original list in place (e.g. new_list = items[1:]).