Skip to content

Python list pop first element | Example code

  • by

Use the del keyword or pop() function to pop the first element from a list in Python. These both will modify the given original list.

list.pop(index)
del list[index]

Python list pop first example

Simple example code.

Using pop() function

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

Output:

Python list pop first element

Using del keyword

It will not return an element. Use the del keyword and the slicing notation [0] to access and remove the first element from a list

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

print(l)

Output: [‘b’, ‘c’, ‘d’]

Slicing

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

print(x)

Output: [1, 2, 3, 4]

Python list pop first-time complexity

list.pop() with no arguments removes the last element. Accessing that element can be done in constant time. There are no elements following so nothing needs to be shifted.

list.pop(0) removes the first element. All remaining elements have to be shifted up one step, so that takes O(n) linear time.

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on this Python list topic,

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *