How to Remove From List in Python

Remove from Python list

To remove the last value from a list in Python, use the pop() method.

For example:

nums = [100, 200, 300]

nums.pop()

# nums is now [100, 200]

To remove a value from a list at a specific index, use the pop() method by providing it an index.

For example, let’s remove the first element of a list:

nums = [100, 200, 300]

nums.pop(0)

How to Remove from List in Python

There are five main ways to remove stuff from lists in Python:

  1. The pop() method.
  2. The clear() method.
  3. The remove() method.
  4. The del statement.
  5. List comprehensions/filtering to remove items that meet a criterion

Here is a short cheat sheet for using these five approaches.

# 1. The pop() mehthod - remove an element at a specific index
names = ["Alice", "Bob", "Charlie"]
names.pop(0) # remove the first name, that is, "Alice" from the list

# 2. The clear() method — wipe out the whole list
numbers = [1, 2, 3, 4, 5]
numbers.clear() # remove everything from the list

# 3. The remove() method — removes the first occurrence of a specific string
names = ["Alice", "Bob", "Charlie", "Bob"]
names.remove("Bob") # Remove the first "Bob" from the list.

# 4. The del statement - remove the whole list or remove a specific element from it
numbers = [1, 2, 3, 4, 5]
del numbers[0] # Remove the first number from the list
del numbers    # Destroy the whole list

# 5. List comprehensions and filtering — remove elements that meet a criterion
names = ["Alexander", "Rob", "John", "David", "Emmanuel"]
short_names = [name for name in names if len(name) < 5]       # Create a list of names less than 5 long
short_names = list(filter(lambda name: len(name) < 5, names)) # Another way to create a list of names less than 5 long

Let’s go through each of these approaches in more detail with examples and simple explanations.

1. Pop() Method

The pop() method is a built-in list method in Python. It removes and returns a value from a list. Trying to remove a non-existent item causes an error.

There are two ways you can use the pop() method in Python:

  1. Call pop() without arguments. This removes and returns the last element of a list.
  2. Call pop() with an argument. It is an integer that specifies the index at which an element is removed from the list.

For example:

names = ["Alice", "Bob", "Charlie"]
names.pop()

# Now names is ['Alice', 'Bob']

As another example, let’s remove the first element:

names = ["Alice", "Bob", "Charlie"]
names.pop(0)

# Now names is ['Bob', 'Charlie']

Remember that the pop() method returns the removed value. This is useful if you want to use the removed value somewhere.

For example, let’s print the removed value and the end result:

names = ["Alice", "Bob", "Charlie"]

print(f"After removing {names.pop(0)} the names list is {names}")

Output:

After removing Alice the names list is ['Bob', 'Charlie']

If you try to remove a non-existent item from the list, an IndexError is thrown:

names = ["Alice", "Bob", "Charlie", "Bob"]
names.pop(10)

# IndexError: pop index out of range

2. Clear() Method

The clear() method has one job. It wipes out the whole list.

Using clear() is easy—just call it on any list.

For example:

numbers = [1, 2, 3, 4, 5]
numbers.clear()

# Result: []

3. Remove() Method

To remove the first occurrence of a specific element from a list, use the remove() method.

For instance:

names = ["Alice", "Bob", "Charlie", "Bob"]
names.remove("Bob")

# Now the names list is: ['Alice', 'Charlie', 'Bob']

Notice how there were two elements called "Bob" in the list. Thus, only the first one was removed by the remove() method.

If you try to remove a non-existent value, an error is produced:

names = ["Alice", "Bob", "Charlie", "Bob"]
names.remove("Something else")

# ValueError: list.remove(x): x not in List

4. Del Statement in Python

The three previous ways to remove from Python lists are built-in to lists.

However, you can also use a del statement to remove items from a list. This statement is not built-in to work with lists only. You can delete other Python objects with it too.

Let’s have a look at some examples of removing values from a list using the del statement:

numbers = [1, 2, 3, 4, 5]

del numbers[0]

# Now numbers is: [2, 3, 4, 5]

Using the del statement, you can delete a range of items in a list.

For example, let’s remove values 2,3,4 from the list of numbers:

numbers = [1, 2, 3, 4, 5]

del numbers[1:4]

# Now numbers is [1, 5]

In general, to remove a slice of values, use the del statement with this syntax:

del list[start: end + 1]

Where:

  • start is the starting index
  • end is the last index you want to remove. But due to how slicing works in Python, add one to the last index to really remove at the last index.

5. Remove from List Using Filtering in Python

This is not directly removing values from a list. Instead, you can create a new list where you have removed values that meet a criterion.

There are two ways to filter lists in Python:

  1. List Comprehension
  2. The built-in filter() function

Let’s go through both of these approaches:

List Comprehension

In case you don’t know what list comprehension is, it is a shorthand for a for loop.

For example, here you can easily see how a list comprehension can compress a for loop nicely:

numbers = [1, 2, 3, 4, 5]

# Square a list of values using a for loop
squared_nums = []
for num in numbers:
    squared_nums.append(num ** 2)

# Square a list of numbers using a list comprehension
squared_nums = [num ** 2 for num in numbers]

Now, just like using a regular for loop, you can use a list comprehension to filter a list.

For example, let’s remove all the odd numbers from a list of numbers using a list comprehension:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

odds = [num for num in numbers if num % 2 == 0]

# [2, 4, 6, 8, 10]

Filter() Function

You can also use filter() function to filter values from a list. This creates a filter object, which you can turn to a list using the built-in list() function. This Python’s built-in method does not directly remove from list either but rather creates a copy with the filtered values.

The filter function takes two parameters:

  1. A filtering function. This can be a lambda expression or a reference to an existing function.
  2. The list (or any other iterable) to be filtered.

Let’s see the same example of filtering odd values from a list:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# filter the list of numbers
odds = filter(lambda num: num % 2 == 0, numbers)

# Convert filter object to a list
odds = list(odds)

# [2, 4, 6, 8, 10]

Conclusion

To remove from a list in Python, you can use:

  • The pop() method
  • The clear() method.
  • The remove() method
  • The del statement.
  • List comprehensions/filtering to remove items that meet a criterion

Thanks for reading. I hope you enjoy it.

Happy coding!

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published.