Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Using Python remove()
2.1.
Example
2.2.
Python
3.
Using Python del
3.1.
Example
3.2.
Python
3.3.
Python
4.
Using Python List Comprehension
4.1.
Example
4.2.
Python
4.3.
Python
5.
Using Python pop()
5.1.
Example
5.2.
Python
5.3.
Python
6.
Using Python discard()
6.1.
Example
6.2.
Python
6.3.
Python
7.
Using Python filter()
7.1.
Example
7.2.
Python
8.
How It Works
8.1.
Python
9.
Using Python List Slicing
9.1.
Example
9.2.
Python
9.3.
Python
10.
Frequently Asked Questions
10.1.
What happens if I try to remove an element from a list that isn't there using remove()?
10.2.
Can I use pop() to remove an item from anywhere in the list?
10.3.
How do I remove multiple specific items from a list in Python?
11.
Conclusion
Last Updated: May 25, 2024
Medium

Remove Element From List Python

Author Riya Singh
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Python lists are a powerful tool for storing & managing collections of data. Sometimes, you may need to remove specific elements from a list. Python provides several ways to achieve this, depending on your requirements. 

Remove Element From List Python

In this article, we will learn various methods to remove elements from a Python list, including using remove(), del, list comprehension, pop(), discard(), filter(), & list slicing. 

Using Python remove()

The remove() method in Python is straightforward: it deletes the first occurrence of a specified element from the list. This is particularly useful when you know exactly what element you want to remove, but its position in the list is unknown or irrelevant.

Example

Consider you have a list of fruit names, and you need to remove "apple" from the list.

  • Python

Python

fruits = ["apple", "banana", "cherry", "apple"]
fruits.remove("apple")
print(fruits)

Output

['banana', 'cherry', 'apple']


Notice how only the first "apple" was removed. If you need to remove all occurrences, you would need to use a loop or another method, which we will discuss later.

This method throws a ValueError if the element is not found in the list, so it's often wise to check if the element is in the list before attempting to remove it.

if "apple" in fruits:
    fruits.remove("apple")


This ensures that your program won’t crash if "apple" isn’t in the list when you try to remove it. Using remove() is a direct & effective way to handle list elements, making your code cleaner & more readable.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Using Python del

The del statement in Python is a powerful tool for modifying lists, allowing you to remove elements by their index rather than their value. This method is ideal when you know the exact position of the element you want to eliminate from the list.

Example

Imagine you have a list of numbers and you want to remove the third element.

  • Python

Python

numbers = [10, 20, 30, 40, 50]
del numbers[2] # Removes the element at index 2 (which is 30)
print(numbers)

Output

[10, 20, 40, 50]


The del statement can also remove slices of a list, which means multiple elements at once, if you specify a range of indices.

  • Python

Python

numbers = [10, 20, 30, 40, 50]

del numbers[1:3]  # Removes elements at index 1 and 2

print(numbers)

Output:

[10, 40, 50]


One of the advantages of using del is that it directly modifies the list. However, you must be cautious because using an invalid index will result in an IndexError, potentially crashing your program if not handled properly. Always ensure the index exists before using del to avoid errors.

This method does not return the removed element; it simply deletes it from the list, making it a straightforward choice for list management when element positions are known.

Using Python List Comprehension

List comprehension in Python provides a concise way to create and manipulate lists. One of its uses is to filter elements out of a list, effectively removing items based on a condition. This method is not only succinct but also often more readable compared to looping structures.

Example

Suppose you have a list of numbers and want to remove all instances of the number 20.

  • Python

Python

numbers = [10, 20, 30, 20, 40, 20]

numbers = [num for num in numbers if num != 20]

print(numbers)

Output:

[10, 30, 40]


In this list comprehension, num for num in numbers if num != 20 generates a new list including only those numbers that are not equal to 20. This approach is highly efficient for filtering out unwanted values without altering the original list structure.

List comprehension is especially powerful because it can be adapted for more complex conditions, and it's very readable. For instance, if you want to remove numbers greater than 25:

  • Python

Python

numbers = [10, 20, 30, 20, 40, 20]

numbers = [num for num in numbers if num <= 25]

print(numbers)

Output:

[10, 20, 20, 20]


This method ensures that only the elements meeting the condition remain in the list, effectively removing those that do not. It's a flexible tool that can be tailored to diverse needs, making your code efficient and clean.

Using Python pop()

The pop() method in Python is another effective way to remove elements from a list, but unlike remove(), it works with indices and also returns the removed element. This feature is particularly useful when you need to not only delete an item but also use it later in your program.

Example

Let's say you have a list of cities, and you want to remove the last city in the list.

  • Python

Python

cities = ["New York", "Los Angeles", "Chicago", "Houston"]

removed_city = cities.pop()  # By default, it removes the last item

print("Removed City:", removed_city)

print("Remaining Cities:", cities)

Output:

Removed City: Houston
Remaining Cities: ["New York", "Los Angeles", "Chicago"]


You can also specify the index of the element you want to remove. If you need to remove the city "Los Angeles" (which is at index 1):

  • Python

Python

cities = ["New York", "Los Angeles", "Chicago", "Houston"]

removed_city = cities.pop(1)

print("Removed City:", removed_city)

print("Remaining Cities:", cities)

Output:

Removed City: Los Angeles
Remaining Cities: ["New York", "Chicago", "Houston"]

 

If an invalid index is given, pop() will raise an IndexError, so it’s good practice to ensure that your index is within the bounds of the list.

index = 5  # An index that does not exist in the list
if index < len(cities):
    removed_city = cities.pop(index)
    print("Removed City:", removed_city)
else:
    print("Index is out of the list bounds.")

 

The pop() method offers both the functionality to remove elements by index and to retrieve the removed item, making it versatile for scenarios where both actions are needed.

Using Python discard()

It's important to note that the discard() method is not applicable directly to lists in Python; it is used with sets. However, understanding how to use discard() can still be beneficial for managing collections of unique items, especially when you need to remove elements without errors if the item doesn't exist.

Example

Imagine you have a set of unique book titles, and you want to remove "The Great Gatsby" from the set.

  • Python

Python

books = {"1984", "The Great Gatsby", "To Kill a Mockingbird", "The Catcher in the Rye"}

books.discard("The Great Gatsby")  # Removes "The Great Gatsby" from the set

print(books)

Output:

{'1984', 'To Kill a Mockingbird', 'The Catcher in the Rye'}


The advantage of discard() over methods like remove() for sets is that it does not raise an error if the specified element is not present in the set. This makes it safer for use when you are unsure whether an item is included in the set or not.

If you attempted to remove "The Great Gatsby" again, nothing would happen, and no error would be raised:

  • Python

Python

books.discard("The Great Gatsby")

print(books)

Output:

{'1984', 'To Kill a Mockingbird', 'The Catcher in the Rye'}


While discard() is specific to sets, you can sometimes use sets temporarily in list manipulation tasks to efficiently remove duplicates or unwanted items, especially when the order of items is not important. You would convert your list to a set, use discard(), and then convert it back to a list if necessary.

This method is particularly useful in scenarios where avoiding errors and exceptions is crucial, providing a fail-safe option for removing items.

Using Python filter()

The filter() function in Python allows you to create a new iterator from elements of an iterable (like a list) for which a function returns true. In simpler terms, it helps you remove elements from a list based on a condition, similar to list comprehension but often clearer and more functional in style.

Example

Assume you have a list of ages, and you want to filter out all ages under 18, which might represent a list of people eligible to vote.

  • Python

Python

ages = [14, 22, 17, 24, 16, 29]

adult_ages = list(filter(lambda age: age >= 18, ages))

print(adult_ages)

Output:

[22, 24, 29]

In this code, filter() uses a lambda function lambda age: age >= 18 as its first argument. This function checks if each age is 18 or older. The filter() function applies this check to each element in the ages list and returns only those elements that satisfy the condition.

How It Works

Lambda Function: This is a small anonymous function defined with the lambda keyword. It takes an argument and evaluates an expression for that argument.

Filter Function: The filter() takes two arguments: a function and an iterable. The function is applied to each item of the iterable, and filter() creates a new iterable (like a list or a set) made only of items for which the function returns True.

This method is beneficial when working with more complex conditions or when you wish to use a function multiple times across different data sets. It's efficient, readable, and directly supports functional programming styles in Python.

  • Python

Python

# More complex example with a defined function

def is_adult(age):

   return age >= 18


adult_ages = list(filter(is_adult, ages))

print(adult_ages)

Output:

[22, 24, 29]


Using filter() can be particularly useful for larger data sets where readability and reusability of filtering logic are key. It seamlessly integrates with other Python functions and promotes clean, readable code.

Using Python List Slicing

List slicing in Python provides a highly flexible way to handle parts of lists. Slicing allows you to create a new list containing only a specified segment of an original list. This can be incredibly useful for removing items from the beginning, middle, or end of a list by omitting them from the slice.

Example

Suppose you have a list of months and you want to keep only the months from March to August.

  • Python

Python

months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

spring_to_summer = months[2:8]  # Slices from index 2 (March) to 7 (August)

print(spring_to_summer)


Output:

['March', 'April', 'May', 'June', 'July', 'August']


How It Works:

  • Start Index: The position where the slice starts (inclusive).
     
  • End Index: The position where the slice ends (exclusive).
     
  • Step: (Optional) The interval between elements to slice. By default, it's 1, meaning it takes every element in the range.
     

Slicing can also be used to remove elements by creating slices before and after the item or items you want to remove, and then combining them.

For example, if you want to remove "May" from the list:

  • Python

Python

# May is at index 4

months_without_may = months[:4] + months[5:]

print(months_without_may)

Output:

['January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December']


This method is particularly efficient when you need to work with contiguous segments of a list. It avoids the need for loops or more complex list comprehensions for removing elements, making the code simpler and easier to understand.

List slicing is not only about removing elements; it's also a powerful tool for rearranging or reversing lists quickly. For instance, to reverse the list of months:

reversed_months = months[::-1]
print(reversed_months)


Output:

['December', 'November', 'October', 'September', 'August', 'July', 'June', 'May', 'April', 'March', 'February', 'January']


Using list slicing effectively can greatly simplify your Python code, making it more readable and maintainable. Whether you're trimming lists, selecting specific sections, or rearranging their order, slicing offers a clean and concise approach.

Frequently Asked Questions

What happens if I try to remove an element from a list that isn't there using remove()?

Using remove() on an element that doesn't exist in the list will cause a ValueError. To avoid this, you can check if the element is in the list before attempting to remove it.

Can I use pop() to remove an item from anywhere in the list?

Yes, pop() can remove an item at a specific index, which you provide as an argument. If no index is provided, pop() removes the last item of the list.

How do I remove multiple specific items from a list in Python?

To remove multiple specific items, you could use list comprehension to create a new list that only includes items that do not meet the removal criteria. For example, [x for x in original_list if x not in items_to_remove].

Conclusion

In this article, we've learned various methods to remove elements from lists in Python, each suited for different scenarios and needs. From remove() for deleting specific values to del for removing elements by index, and from list comprehension for filtering out items to pop() for extracting and removing by index. We also covered set-specific discard() and functional-style filter(), as well as the versatile slicing technique which helps in selecting or omitting specific sections of a list.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Next article
Python Introduction
Live masterclass