Coder Perfect

How do I get rid of the first item in a list?

Problem

[0, 1, 2, 3, 4] is the list I have. [1, 2, 3, 4] is what I’d like to do with it. What’s the best way to go about it?

Asked by rectangletangle

Solution #1

A brief list of helpful list functions can be found here.

list.pop(index)

>>> l = ['a', 'b', 'c', 'd']
>>> l.pop(0)
'a'
>>> l
['b', 'c', 'd']
>>> 

del list[index]

>>> l = ['a', 'b', 'c', 'd']
>>> del l[0]
>>> l
['b', 'c', 'd']
>>> 

Both of these alter your original.

Slicing has been suggested by others:

Also, if you’re doing a lot of pop(0), you might consider using collections. deque

from collections import deque
>>> l = deque(['a', 'b', 'c', 'd'])
>>> l.popleft()
'a'
>>> l
deque(['b', 'c', 'd'])

Answered by kevpie

Solution #2

Slicing:

x = [0,1,2,3,4]
x = x[1:]

This would return a subset of the original but would not change it.

Answered by justin.m.chase

Solution #3

>>> x = [0, 1, 2, 3, 4]
>>> x.pop(0)
0

More on this can be found here.

Answered by user225312

Solution #4

You’d simply do it.

l = [0, 1, 2, 3, 4]
l.pop(0)

or l = l[1:]

Pros and Cons

You may get the value using pop.

If x = l.pop(0) was used, the result would be 0.

Answered by Zimm3r

Solution #5

For additional information on list slicing, consult the Python tutorial on lists:

>>> l = [0, 1, 2, 3, 4]
>>> l[1:]
[1, 2, 3, 4]

Answered by Haes

Post is based on https://stackoverflow.com/questions/4426663/how-to-remove-the-first-item-from-a-list