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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots