Remove The First (or Any) Item from a Python List
TL;DR
I use to yoink the first item out of python lists.
=
['bravo', 'charlie', 'delta']
Details
Pulling First Place
.pop()
returns the value it removes. You can capture it in a variable.
=
=
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.
=
=
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 is way more versatile.
-a
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. =
).