Learn How to Delete the Head of Your Python List

This tutorial teaches you how to remove the first element from a Python list using simple code examples and clear explanations. …

Updated August 26, 2023



This tutorial teaches you how to remove the first element from a Python list using simple code examples and clear explanations.

Imagine you have a shopping list stored as a Python list:

shopping_list = ["apples", "bananas", "milk", "bread"]

You just bought apples, so you want to remove them from the list. In Python, this is done using the pop() method.

Understanding the pop() Method:

The pop() method is like a pair of hands that can grab an element from your list and remove it. By default, pop() removes and returns the last element in the list. However, we can tell it which element to remove by specifying its index.

Removing the First Element:

Since Python uses zero-based indexing (the first element is at index 0), we use:

shopping_list.pop(0)
print(shopping_list)

This code does the following:

  1. shopping_list.pop(0): This calls the pop() method on our list (shopping_list) and tells it to remove the element at index 0 (the first element). The removed element (“apples” in this case) is also returned by the pop() method, but we aren’t using it here.

  2. print(shopping_list): This prints the updated list:

['bananas', 'milk', 'bread'] 

Typical Mistakes and Tips:

  • Forgetting the Index: If you omit the index within pop(), it will remove the last element, not the first.

  • Trying to Pop from an Empty List: Attempting to pop() an empty list will result in an “IndexError”. Always check if your list has elements before using pop().

When to Use Other Methods:

  • Deleting by Value: If you need to remove a specific value from the list (not necessarily the first occurrence), use the remove() method. For example:
shopping_list = ["apples", "bananas", "milk", "bread"]
shopping_list.remove("milk") 
print(shopping_list)  # Output: ['apples', 'bananas', 'bread']

Building on Previously Taught Concepts:

  • Lists: This concept builds directly upon understanding how lists work in Python, including indexing and element access.

  • Methods: pop() is a method – a function associated with an object (in this case, the list). Learning methods allows you to manipulate data efficiently.

Let me know if you have any other questions!


Stay up to date on the latest in Computer Vision and AI

Intuit Mailchimp