How to Remove an Element from a List in Python

by | Programming, Python, Tips

Removing elements from a list is a common task in Python. We typically do element removal during data cleaning.

This tutorial will go through the various ways to remove an element or multiple elements from a list in Python with the help of code examples.


Remove First Element from List in Python

Using pop()

The pop() method removes the ith element from a list. If you set i to 0, you will remove the first element in the list. The pop() method changes the original list in place, so there is no need to assign the updated list to a new variable. Let’s look at an example:

lst = [2, 4, 6, 8, 10]

print("Original list is: " + str(lst))

lst.pop(0)

print("Modified list is: " + str(lst))
Original list is: [2, 4, 6, 8, 10]
Modified list is: [4, 6, 8, 10]

Using del

The del method performs the removal of an element in place. We need to specify the list and the index of the value we want to remove. In this case, the index is 0 to remove the first element in the list. Let’s look at an example:

lst = [2, 4, 6, 8, 10]

print("Original list is: " + str(lst))

del lst[0]

print("Modified list is: " + str(lst))
Original list is: [2, 4, 6, 8, 10]
Modified list is: [4, 6, 8, 10]

Using Slicing

We can slice the list to select a subset of elements from the original list. If we want to remove the first element, we start the slice with the second element index to the last and assign it to a new variable. Slicing does not do in-place element removal. Let’s look at an example:

lst = [2, 4, 6, 8, 10]

print("Original list is: " + str(lst))

mod_lst = lst[1:]

print("Modified list is: " + str(mod_lst))
Original list is: [2, 4, 6, 8, 10]
Modified list is: [4, 6, 8, 10]

Remove Last Element from List in Python

Using pop()

Similar to removing the first element, we can call the pop method on the list. However, the default for the pop() method is to remove the last element in the list, so we do not need to specify an index in this case. Le’s look at an example.

lst = [2, 4, 6, 8, 10]

print("Original list is: " + str(lst))

lst.pop()

print("Modified list is: " + str(lst))
Original list is: [2, 4, 6, 8, 10]
Modified list is: [2, 4, 6, 8]

Using del

We can use the del method to remove the last element in the list by specifying the list and the index -1. The index -1 signifies the first value from the end of the list (reverse indexing) or the last element. Let’s look at an example:

lst = [2, 4, 6, 8, 10]

print("Original list is: " + str(lst))

del lst[-1]

print("Modified list is: " + str(lst))
Original list is: [2, 4, 6, 8, 10]
Modified list is: [2, 4, 6, 8]

Using Slicing

We can slice the list to select a subset of elements from the original list. If we want to remove the last element, we start the slice from the start of the list to the last element and assign it to a new variable. The index of the last element is -1. Let’s look at an example:

lst = [2, 4, 6, 8, 10]

print("Original list is: " + str(lst))

mod_lst = lst[:-1]

print("Modified list is: " + str(mod_lst))
Original list is: [2, 4, 6, 8, 10]
Modified list is: [2, 4, 6, 8]

Remove Multiple Elements from List in Python

Using List Comprehension

To remove multiple values, we can use a list comprehension, which creates a new list based on the condition we apply to the elements in the list. Let’s look at the example code:

lst = [2, 4, 6, 8, 10, 12]

print("Original list is: " + str(lst))

nums_to_remove = [4, 8, 10]

lst2 = [i for i in lst if i not in nums_to_remove]

print("List with unwanted numbers removed: ", str(lst2))

We specify a subset of numbers that we do not want in the list in this example. Then we use a list comprehension to put the elements in the list if they are not in the subset list. Let’s run the code to see the result.

Original list is: [2, 4, 6, 8, 10, 12]
List with unwanted numbers removed:  [2, 6, 12]

Remove Element from List by Index in Python

Using del

We can use the del method to delete specific elements in a list by specifying the index. Let’s look at an example of removing the third element in the list.

lst = [2, 4, 6, 8, 10, 12]

print("Original list is: " + str(lst))

del lst[2]

print("Modified list: ", str(lst))
Original list is: [2, 4, 6, 8, 10, 12]
Modified list:  [2, 4, 8, 10, 12]

Using Slicing

We can use the del method to delete multiple elements, and we have to specify a slice to select the values to delete. Let’s look at an example:

lst = [2, 4, 6, 8, 10, 12]

print("Original list is: " + str(lst))

del lst[2:5]

print("Modified list: ", str(lst))

In the above example, we delete the elements from the index 2 to 4 as a slice does not include the element at the end of the slice. Let’s run the code to get the output:

Original list is: [2, 4, 6, 8, 10, 12]
Modified list:  [2, 4, 12]

Remove None from List in Python

None is a common value that we would want to remove from a list. There are several ways we can do this.

Naive Method

We can iterate over a list using a for loop and check if the element is not equal to None. If not, we append the value to an empty list. Once the for loop completes, the empty list will have the values that are not None. Let’s look at an example:

lst = [2, None, None, 4, 6, 8, None, 10, None]

print("Original list is: " + str(lst))

lst2 = []

for value in lst:
    if value != None:
        lst2.append(value)

print("List with None value removed: " + str(lst2))
Original list is: [2, None, None, 4, 6, 8, None, 10, None]
List with None value removed: [2, 4, 6, 8, 10]

Using List Comprehension

We can use a list comprehension to select elements in a list that are not None values. Let’s look at an example:

lst = [2, None, None, 4, 6, 8, None, 10, None]

print("Original list is: " + str(lst))

lst2 = [i for i in lst if i]

print("List with None value removed: " + str(lst2))
Original list is: [2, None, None, 4, 6, 8, None, 10, None]
List with None value removed: [2, 4, 6, 8, 10]

Using filter()

The filter() method is a concise way to remove the None values from a list. The syntax of the filter() method is:

filter(function, iterable)

Parameters:

  • function: Function to run for each item in the iterable
  • iterable: Iterable to filter

The method returns an iterator, which contains the filtered items. We need to convert that back to a list using the list() method. In this example, the filter is None, and the iterable is the list we want to remove None from.

lst = [2, None, None, 4, 6, 8, None, 10, None]

print("Original list is: " + str(lst))

lst2 = list(filter(None, lst))

print("List with None value removed: " + str(lst2))
Original list is: [2, None, None, 4, 6, 8, None, 10, None]
List with None value removed: [2, 4, 6, 8, 10]

Remove NaN from List in Python

NaN value in programming stands for Not a Number. If a NaN value exists in an array or a list, it can cause problems during calculations on the list. We can remove the NaN and the string ‘nan’ from the list using the following methods.

Using math.isnan()

The isnan() method from the math library takes a number and returns True if the value is a NaN; otherwise, it returns False. We can use list comprehension to create a new list with elements that are not NaN values. Let’s look at an example:

import math

lst = [2, float('nan'), float('nan'), 4, 6, 8, float('nan'), 10, float('nan')]

print("Original list is: " + str(lst))

lst2 = [i for i in lst if math.isnan(i) == False]

print("List with NaN value removed: " + str(lst2))
Original list is: [2, nan, nan, 4, 6, 8, nan, 10, nan]
List with NaN value removed: [2, 4, 6, 8, 10]

The isnan() method from the NumPy library takes a number and returns True if the value is a NaN; otherwise, it returns False. We can use list comprehension to create a new list with elements that are not NaN values using numpy.isnan(). Let’s look at an example:

Using numpy.isnan()

import numpy as np

lst = [2, float('nan'), float('nan'), 4, 6, 8, float('nan'), 10, float('nan')]

print("Original list is: " + str(lst))

lst2 = [i for i in lst if np.isnan(i) == False]

print("List with NaN value removed: " + str(lst2))
Original list is: [2, nan, nan, 4, 6, 8, nan, 10, nan]
List with NaN value removed: [2, 4, 6, 8, 10]

Using pandas.isnull()

The isnull() method from the Pandas library takes a scalar or an array-like object and returns True if the value is equal to NaN, None or NaT; otherwise, it returns False. We can use list comprehension with pandas.isnull() to remove all NaN values from a list. Let’s look at an example:

import pandas as pd

lst = [2, float('nan'), float('nan'), 4, 6, 8, float('nan'), 10, float('nan')]

print("Original list is: " + str(lst))

lst2 = [i for i in lst if pd.isnull(i) == False]

print("List with NaN value removed: " + str(lst2))
Original list is: [2, nan, nan, 4, 6, 8, nan, 10, nan]
List with NaN value removed: [2, 4, 6, 8, 10]

Removing NaN from a List of Strings in Python

We can encounter lists of numbers converted to strings. In that case, the float value ‘nan’ will be the string value ‘nan’. We can use a list comprehension to remove a ‘nan’ string. Let’s look at an example:

import pandas as pd

lst = ['2', 'nan', 'nan', '4', '6', '8', 'nan', '10', 'nan']

print("Original list is: " + str(lst))

lst2 = [i for i in lst if i != 'nan']

print("List with NaN value removed: " + str(lst2))

The condition in the list comprehension that removes the ‘nan’ strings is if i != ‘nan’. Let’s run the code to get the result:

Original list is: ['2', 'nan', 'nan', '4', '6', '8', 'nan', '10', 'nan']
List with NaN value removed: ['2', '4', '6', '8', '10']

Remove All Occurrences of Element from List in Python

We may want to remove all occurrences of an element from a list in Python. There are several ways to do this in Python.

Using List Comprehension

We can use list comprehension to specify the value we do not want in the list. In the list comprehension, we check if each element is not equal to the value we want to remove. If True, then the element goes into the new list. Otherwise, it does not. Let’s look at an example:

lst = [2, 4, 2, 6, 8, 10, 2, 12, 2, 2]

print("Original list is: " + str(lst))

value_to_remove = 2

lst2 = [i for i in lst if i != value_to_remove]

print("Modified list: ", str(lst2))
Original list is: [2, 4, 2, 6, 8, 10, 2, 12, 2, 2]
Modified list:  [4, 6, 8, 10, 12]

Using Filter and __ne__

We can also use the filter function, where we filter those elements which are not equal to the value we want to remove. We can use the __ne__() method, which returns whether an element in an array is not equal to the value provided as a parameter. Let’s look at an example:

lst = [2, 4, 2, 6, 8, 10, 2, 12, 2, 2]

print("Original list is: " + str(lst))

item = 2

lst2 = list(filter((item).__ne__, lst))

print("Modified list: ", str(lst2))
Original list is: [2, 4, 2, 6, 8, 10, 2, 12, 2, 2]
Modified list:  [4, 6, 8, 10, 12]

Using remove()

In this method, we use a for loop to iterate over each element in the list. If the element matches the value we want to remove, then we call the remove() function on the list to discard that element. Let’s look at an example:

lst = [2, 4, 2, 6, 8, 10, 2, 12, 2, 2]

print("Original list is: " + str(lst))

item = 2

for i in lst:
    if(i==item):
        lst.remove(i)

print("Modified list: ", str(lst2))
Original list is: [2, 4, 2, 6, 8, 10, 2, 12, 2, 2]
Modified list:  [4, 6, 8, 10, 12]

Remove New Line Character from List in Python

Removing stray newline characters “\n” from strings is a common preprocessing task for data analysis. If you want to remove a specific character or characters from each element in a list, you can use replace or the regex library.

Using for loop and replace

In this approach, we use a for loop to iterate over each item in the list and check if a “\n” exists in each. We then call the replace() method to remove the “\n” character. Let’s look at an example:

# Initialize list
lst =["Python\n", "is", "re\nally", "f\nun", "to", "lear\nn"]

# Print list
print("The original list is :" + str(lst))

# New empty list
lst2 = []

# Removing newline character from string using for loop
for string in lst:
    lst2.append(string.replace("\n",""))

# Print result
print("Modified list: ", str(lst2))
The original list is :['Python\n', 'is', 're\nally', 'f\nun', 'to', 'lear\nn']
Modified list:  ['Python', 'is', 'really', 'fun', 'to', 'learn']

Using regex

We can import the regex library to replace all the newline characters with an empty string globally. The regex method is preferable because it checks for all occurrences of the newline character, whereas the replace method only removes one occurrence. Let’s look at an example.

# Import regex 
import re

# Initialize list
lst =["Python\n", "is", "re\nally", "f\nun", "to", "lear\nn"]

# Print list
print("The original list is :" + str(lst))

# Removing newline character from string using regex in for loop
lst2 = []

for string in lst:
    lst2.append(re.sub("\n",'',string)

# Print result
print("Modified list: ", str(lst2))
The original list is :['Python\n', 'is', 're\nally', 'f\nun', 'to', 'lear\nn']
Modified list:  ['Python', 'is', 'really', 'fun', 'to', 'learn']

Remove Brackets from List in Python

To remove brackets from a list, we can convert the list to a string using the join() method. Let’s look at an example:

lst = ['a','b','c','d','e','f']

print("Original list is: " + str(lst))

lst2 = (', '.join(lst))

print("List with brackets removed", lst2)

type(lst2)

In the above example, we use the comma character as the delimiter. Let’s run the code to get the result:

Original list is: ['a', 'b', 'c', 'd', 'e', 'f']
List with brackets removed a, b, c, d, e, f
str

Remove Commas from List in Python

To remove the commas from the list, we can convert the list to a string then split the string using the comma delimiter. Then we can join the split strings together to a single string using the join() method. The result is a string. Let’s look at an example:

# Initialize String

lst = ['a','b','c','d','e','f']

print("Original list is: " + str(lst))

# Convert list to string

lst_string = str(lst)

# Split string

split_strings = lst_string.split(',')

print("Split up strings: ", split_strings)

# Join the strings 

lst2 = ''.join(split_strings)

print("List with commas removed", lst2)

# Print result 

print(type(lst2))
Original list is: ['a', 'b', 'c', 'd', 'e', 'f']
Split up strings:  ["['a'", " 'b'", " 'c'", " 'd'", " 'e'", " 'f']"]
List with commas removed ['a' 'b' 'c' 'd' 'e' 'f']
<class 'str'>

Remove Duplicates from a List in Python

To learn how to remove duplicates from a list and only retain unique values, go to the article: How to Get Unique Values from List in Python.

Summary

Congratulations on reading to the end of this tutorial! You have gone through the different ways to remove elements from a list, and it is up to you what method you choose to remove an element. The most common approaches are list comprehension and the filter method.

For further reading on list manipulation, go to the article: How to Flatten a List of Lists in Python.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨