Sling Academy
Home/Python/Python: How to Remove Elements from a List (4 Approaches)

Python: How to Remove Elements from a List (4 Approaches)

Last updated: June 10, 2023

This concise, straightforward article will walk you through a couple of different ways to remove one or many elements from a list in Python 3.

Using the remove() method

The remove() method helps you remove a specific element from a list by its value. This approach is simple and intuitive to use and does not require knowing the index of the element. However, there are some downsides you should be aware of:

  • It only removes the first occurrence of the value.
  • It takes more time to iterate if the element is at the end of the list.
  • A ValueError will be raised if the value you passed is not present in the list (this can be solved by using a check).

Example:

my_list = ['sling', 'academy', 'dog', 'turtle', 'dog', 'turkey', 'dog']
my_list.remove('dog')
print(my_list)

Output:

['sling', 'academy', 'turtle', 'dog', 'turkey', 'dog']

Using the remove() method with a check to avoid ValueError:

my_list = ['sling', 'academy', 'dog', 'turtle', 'dog', 'turkey', 'dog']

value_to_remove = 'dragpm'

if value_to_remove in my_list:
    my_list.remove(value_to_remove)
else:
    print(f'{value_to_remove} is not in the list')

Using the del statement

The del statement delete an element from a given list by its index number or a slice of elements by a range of indices. This statement is flexible and versatile and can be used to remove multiple elements at once by slicing. However, it requires knowing or finding the index or range of indices of the elements (which you want to discard).

Example:

# Create a list of games
games = ["League of Legends", "CS:GO", "Valorant", "Dota 2", "PUBG"]

# Delete the second element (index 1) from the list
del games[1]

# Print the updated list
print(games)

# Delete the last two elements (indices -2 and -1) from the list
del games[-2:]

# Print the updated list
print(games)

Output:

['League of Legends', 'Valorant', 'Dota 2', 'PUBG']
['League of Legends', 'Valorant']

Using the pop() method

The pop() method removes and returns an element from the list by its index number. If no index is provided, it will remove and return the last element of the list.

Pros: It is fast and efficient to use. It can be used to get the removed element as a return value.

Cons: It raises an IndexError if the list is empty or the index is out of range and requires knowing or finding the index of the element. This approach is also limited to removing one element at a time.

Example:

# Create a list of years
years = [2023, 2024, 2025, 2026, 2027, 2028]

# Remove and return the third element (index 2) from the list
num = years.pop(2)

# Print the removed element
print(f"Removed element: {num}")

# Print the updated list
print(f"Updated list: {years}")

Output:

Removed element: 2025
Updated list: [2023, 2024, 2026, 2027, 2028]

Using list comprehension

You can also use list comprehension to create a new list by filtering out the elements that match a certain condition from the original list.

Props: It is concise and elegant to use. It can remove multiple elements at once by using a logical expression. It does not modify the original list.

Cons: It creates a new list object, which may consume more memory. It may be less readable for complex conditions.

Example:

sample_list = [
    {
        "name": "Wolf",
        "age": 99
    },
    {
        "name": "Sling Academy",
        "age": 5
    },
    {
        "name": "Pennywise the Dancing Clown",
        "age": 99999
    }
]

# remove ones that are older than 200
sample_list = [x for x in sample_list if x["age"] < 200]
print(sample_list)

Output:

[{'name': 'Wolf', 'age': 99}, {'name': 'Sling Academy', 'age': 5}]

Next Article: Python: How to Find All Occurrences of a Value in a List

Previous Article: Python: 3 Ways to Select Random Elements from a List

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types