Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (84 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

Python Remove List: How to remove element from Lists

Last updated on Apr 26,2024 852.4K Views


Masters in Python programming Certification is one of the most sought certifications in the market after someone completes the Python course examinations such as PCEP, PCAP, PCPP. The reason for this is the array of functionalities Python offers. Lists are one collection that simplifies the life of programmers to a great extent. In this article, we shall learn one such feature that is how to remove elements from lists.

Python Full Course – Learn Python in 12 Hours | Python Tutorial For Beginners | Edureka

This Edureka Python Full Course helps you to became a master in basic and advanced Python Programming Concepts.

Before moving on, let’s take a quick look at all that is covered in this article:

Why use Lists?
What are Lists?
Remove Elements from List using:

So let’s get started. :)

Why use Lists?

Sometimes, there may be situations where you need to handle different types of data at the same time. For example, let’s say, you need to have a string type element, an integer and a floating-point number in the same collection. Now, this is fairly impossible with the default data types that are available in other programming languages like C & C++. In simple words, if you define an array of type integer, you can only store integers in it. This is where Python has an advantage. With its list collection data type, we can store elements of different data types as a single ordered collection! 

Now that you know how important lists are, let’s move on to see what exactly are Lists and how to remove elements from list!

Upskill for Higher Salary with PySpark Certification Training Course

Course NameUpcoming BatchesFees
Pyspark Certification Training27th April,2024 (Weekend Batch)₹21,995
Pyspark Certification Training1st June,2024 (Weekend Batch)₹21,995

What are Lists?

Lists are ordered sequences that can hold a variety of object types. In other words, a list is a collection of elements which is ordered and changeable. Lists also allow duplicate members. We can compare lists in Python to arrays in other programming languages. But, there’s one major difference. Arrays contain elements of the same data types, whereas Python lists can contain items of different types. A single list may contain data types like strings, integers, floating point numbers etc. Lists support indexing and slicing, just like strings. Lists are also mutable, which means, they can be altered after creation. In addition to this, lists can be nested as well i.e. you could include a list within a list.  

The main reason why lists are an important tool in Python programming is because of the wide variety of the built-in functions it comes with. Lists are also very useful to implement stacks and queues in Python. All the elements in a list are enclosed within ‘square brackets’, and every element in it are separated by a ‘comma’.  

EXAMPLE:


myList = ["Bran",11,3.14,33,"Stark",22,33,11]

print(myList)

 

OUTPUT: [‘Bran’, 11, 3.14, 33, ‘Stark’, 22, 33, 11]


In the above example, we have defined a list called myList. As you can see, all the elements are enclosed within square brackets i.e. [ ] and each element is separated by a comma. This list is an ordered sequence that contains elements of different data types.  

At index 0, we have the string element ‘Bran’.

At index 1, we have an integer 11.

At index 2, we have a floating-point number 3.14.

In this way, we can store elements of different types in a single list.

Now that you have a clear idea about how you can actually create lists, let’s move on to see, how to Remove Elements from Lists in Python.

What is Remove in Python?

In Python, `remove()` is a built-in method that allows you to remove a specific element from a list. It is used to delete the first occurrence of the specified value from the list.

The syntax for using the `remove()` method is as follows:

 

</span>

<span style="font-weight: 400;">list_name.remove(value)</span>

<span style="font-weight: 400;">

 

Here, `list_name` is the name of the list from which you want to remove the element, and `value` is the element that you want to remove.

 

Example:

“`python

fruits = [‘apple’, ‘banana’, ‘orange’, ‘apple’, ‘grapes’]

 

fruits.remove(‘apple’)

print(fruits)

“`

 

Output:

“`

[‘banana’, ‘orange’, ‘apple’, ‘grapes’]

“`

In this example, the first occurrence of the element ‘apple’ is removed from the `fruits` list using the `remove()` method. If the element is not found in the list, it will raise a ValueError, so it’s a good practice to check if the element exists in the list before using `remove()`.

Remove Elements from a List:

There are three ways in which you can Remove elements from List:

  1. Using the remove() method
  2. Using the list object’s pop() method
  3. Using the del operator

Let’s look at these in detail.

List Object’s remove() method:

The remove() method is one of the most commonly used list object methods to remove an item or an element from the list. When you use this method, you will need to specify the particular item that is to be removed. Note that, if there are multiple occurrences of the item specified, then its first occurrence will be removed from the list.  We can consider this method as “removal by item’s value”. If the particular item to be removed is not found, then a ValueError is raised.

Consider the following examples:

EXAMPLE 1:


myList = ["Bran",11,22,33,"Stark",22,33,11]

myList.remove(22)

myList

OUTPUT: [‘Bran’, 11, 33, ‘Stark’, 22, 33, 11]

In this example, we are defining a list called ‘myList’. Note that, as discussed before, we are enclosing the list literal within square brackets. In Example 1, we are using the remove() method to remove the element 22 from myList. Hence, when printing the list using the print(), we can see that the element 22 has been removed from myList.

EXAMPLE 2:


 myList.remove(44)

 

OUTPUT:

Traceback (most recent call last):

   File “<stdin>”, line 1, in 

ValueError: list.remove(x): x not in list2

In Example 2, we use the remove() to remove the element 44. But, we know that the list ‘myList’ does not have the integer 44. As a result, a ‘ValueError’ is thrown by the Python interpreter.

(However, this is a slow technique, as it involves searching the item in the list.)

List Object’s pop() method:

The pop() method is another commonly used list object method. This method removes an item or an element from the list, and returns it. The difference between this method and the remove() method is that, we should specify the item to be removed in the remove() method. But, when using the pop(), we specify the index of the item as the argument, and hence, it pops out the item to be returned at the specified index. If the particular item to be removed is not found, then an IndexError is raised. 

 Consider the following examples: 

EXAMPLE 1:


 myList = ["Bran",11,22,33,"Stark",22,33,11]

 myList.pop(1)

Output: 11

In this example, we are defining a list called ‘myList. In Example 1, we are using the pop( ) method, while passing the argument ‘1’, which is nothing but the index position 1. As you can see from the output, the pop( ) removes the element, and returns it, which is the integer ‘11’.

EXAMPLE 2:


myList

OUTPUT[‘Bran’, 22, 33, ‘Stark’, 22, 33, 11]

Note that, in Example 2, when we print the list myList after calling pop(), the integer 11, which was previously present in myList has been removed.

EXAMPLE 3:


myList.pop(8)

OUTPUT:

Traceback (most recent call last):

   File “<stdin>”, line 1, in 

IndexError: pop index out of range

In Example 3, we use the pop() to remove the element which is at index position 8. Since there is no element at this position, the python interpreter throws an IndexError as shown in output.

(This is a fast technique, as it is pretty straightforward, and does not involve any searching of an item in the list.)

Python del operator:

This operator is similar to the List object’s pop() method with one important difference. The del operator removes the item or an element at the specified index location from the list, but the removed item is not returned, as it is with the pop() method. So essentially, this operator takes the item’s index to be removed as the argument and deletes the item at that index. The operator also supports removing a range of items in the list. Please note, this operator, just like the pop() method, raises an IndexError, when the index or the indices specified are out of range.

Consider the following examples:

EXAMPLE 1:


myList = ["Bran",11,22,33,"Stark",22,33,11]

del myList[2]

myList

OUTPUT: [‘Bran’, 11, 33, ‘Stark’, 22, 33, 11]

In the above example, we are defining a list called ‘myList. In Example 1, we use the del operator to delete the element at index position 2 in myList. Hence, when you print myList, the integer ‘22’ at index position 2 is removed, as seen in the output.

 

EXAMPLE 2:


del myList[1:4]

myList

OUTPUT:  [‘Bran’, 22, 33, 11]

In Example 2, we use the del operator to remove elements from a range of indices, i.e. from index position 1 till index position 4 (but not including 4). Subsequently, when you print myList, you can see the elements at index position 1,2 and 3 are removed. 

EXAMPLE 3:


del myList[7]

OUTPUT:

Traceback (most recent call last):

File “”, line 1, in 

IndexError: list assignment index out of range

In Example 3, when you use the del operator to remove an element at index position 7 (which does not exist), the python interpreter throws a ValueError.

(This technique of removing items is preferred when the user has a clear knowledge of the items in the list. Also, this is a fast method to remove items from a list.)

To summarize, the remove() method removes the first matching value, and not a specified index; the pop() method removes the item at a specified index, and returns it; and finally the del operator just deletes the item at a specified index ( or a range of indices).

How to Delete Elements From the List?

In Python, you can delete elements from a list using several methods. Here are three common ways to do it:

  1. Using `del` statement:

The `del` statement is a simple way to delete elements from a list by specifying the index of the element you want to remove.

“`python

fruits = [‘apple’, ‘banana’, ‘orange’, ‘grapes’]

 

# Deleting the element at index 1 (banana)

del fruits[1]

print(fruits)

“`

Output:

“`

[‘apple’, ‘orange’, ‘grapes’]

“`

  1. Using `pop()` method:

The `pop()` method removes the element at a specified index and returns its value. If you don’t provide an index, it will remove and return the last element.

“`python

fruits = [‘apple’, ‘banana’, ‘orange’, ‘grapes’]

# Removing the element at index 2 (orange)

removed_fruit = fruits.pop(2)

print(“Removed fruit:”, removed_fruit)

print(“Updated list:”, fruits)

“`

Output:

“`

Removed fruit: orange

Updated list: [‘apple’, ‘banana’, ‘grapes’]

“`

  1. Using `remove()` method:

The `remove()` method is used to remove the first occurrence of a specified value from the list.

“`python

fruits = [‘apple’, ‘banana’, ‘orange’, ‘grapes’]

# Removing the element ‘banana’

fruits.remove(‘banana’)

print(fruits)

“`

Output:

“`

[‘apple’, ‘orange’, ‘grapes’]

“`

Note: Be cautious while using the `remove()` method. If the element is not found in the list, it will raise a value error. To avoid this, you can use `if` statements to check if the element exists in the list before removing it.

Choose the appropriate method based on your specific requirements, and ensure that you handle any potential errors that may arise while deleting elements from the list.

Remove an Element having multiple occurrences in the list

If you want to remove all occurrences of a specific element from a list (not just the first occurrence), you can use a loop to iterate through the list and remove the element each time it is found. There are several ways to achieve this in Python. Here are two common approaches:

 

  1. Using a `while` loop:

 

</span>

<span style="font-weight: 400;">fruits = ['apple', 'banana', 'orange', 'banana', 'grapes', 'banana']</span>

&nbsp;

<span style="font-weight: 400;"># Element to remove</span>

<span style="font-weight: 400;">element_to_remove = 'banana'</span>

&nbsp;

<span style="font-weight: 400;"># Using a while loop to remove all occurrences of 'banana'</span>

<span style="font-weight: 400;">while element_to_remove in fruits:</span>

<span style="font-weight: 400;">    fruits.remove(element_to_remove)</span>

<span style="font-weight: 400;">print(fruits)</span>

<span style="font-weight: 400;">

 

Output:

“`

[‘apple’, ‘orange’, ‘grapes’]

“`

  1. Using a list comprehension:

 

</span>

<span style="font-weight: 400;">fruits = ['apple', 'banana', 'orange', 'banana', 'grapes', 'banana']</span>

<span style="font-weight: 400;"># Element to remove</span>

<span style="font-weight: 400;">element_to_remove = 'banana'</span>

<span style="font-weight: 400;"># Using list comprehension to remove all occurrences of 'banana'</span>

<span style="font-weight: 400;">fruits = [fruit for fruit in fruits if fruit != element_to_remove]</span>

<span style="font-weight: 400;">print(fruits)</span>

<span style="font-weight: 400;">

 

Output:

“`

[‘apple’, ‘orange’, ‘grapes’]

“`

Both methods will remove all occurrences of the specified element (‘banana’ in this case) from the list. The first method uses a `while` loop to repeatedly remove the element until it no longer exists in the list. The second method uses list comprehension to create a new list with elements that are not equal to the element to be removed.

Choose the method that best suits your needs and keep in mind the performance implications, especially for large lists, as removing elements from a list can be an expensive operation.

Removing all Elements having multiple occurrences in the list

To remove all elements that have multiple occurrences in a list, you can use a combination of Python’s `collections.Counter` and list comprehension. The `Counter` class from the `collections` module helps count the occurrences of each element in the list, and then you can use list comprehension to filter out elements that occur more than once.

 

Here’s how you can do it:

 

 

</span>

<span style="font-weight: 400;">from collections import Counter</span>

&nbsp;

<span style="font-weight: 400;">fruits = ['apple', 'banana', 'orange', 'banana', 'grapes', 'banana', 'apple', 'orange']</span>

&nbsp;

<span style="font-weight: 400;"># Count occurrences of each element in the list</span>

<span style="font-weight: 400;">element_counts = Counter(fruits)</span>

&nbsp;

<span style="font-weight: 400;"># Get a list of elements that occur more than once</span>

<span style="font-weight: 400;">elements_with_multiple_occurrences = [element for element, count in element_counts.items() if count > 1]</span>

&nbsp;

<span style="font-weight: 400;"># Remove all elements that occur more than once from the original list</span>

<span style="font-weight: 400;">fruits = [fruit for fruit in fruits if fruit not in elements_with_multiple_occurrences]</span>

&nbsp;

<span style="font-weight: 400;">print(fruits)</span>

<span style="font-weight: 400;">

 

 

Output:

“`

[‘grapes’]

“`

In this example, we first use the `Counter` class to count the occurrences of each element in the `fruits` list. Then, we use list comprehension to create a list called `elements_with_multiple_occurrences`, containing elements that have more than one occurrence. Finally, we use another list comprehension to create a new list called `fruits` that contains only the elements that do not have multiple occurrences.

After this process, the `fruits` list will only contain elements that have a single occurrence, effectively removing all elements with multiple occurrences.

Passing the Value as Parameter which is not present in the list

In Python, if you pass a value as a parameter to a function and that value is not present in the list, the function will still execute without any errors. However, it’s essential to handle such cases appropriately to avoid unexpected behavior or incorrect results.

Here’s an example of how you can pass a value as a parameter to a function, even if it’s not present in the list:

 

</span>

<span style="font-weight: 400;">def find_index(my_list, value):</span>

<span style="font-weight: 400;">    try:</span>

<span style="font-weight: 400;">        index = my_list.index(value)</span>

<span style="font-weight: 400;">        print(f"The index of {value} in the list is: {index}")</span>

<span style="font-weight: 400;">    except ValueError:</span>

<span style="font-weight: 400;">        print(f"{value} is not present in the list.")</span>

&nbsp;

<span style="font-weight: 400;">fruits = ['apple', 'banana', 'orange', 'grapes']</span>

&nbsp;

<span style="font-weight: 400;"># Value that is present in the list</span>

<span style="font-weight: 400;">find_index(fruits, 'banana')</span>

&nbsp;

<span style="font-weight: 400;"># Value that is not present in the list</span>

<span style="font-weight: 400;">find_index(fruits, 'watermelon')</span>

<span style="font-weight: 400;">

 

Output:

“`

The index of banana in the list is: 1

watermelon is not present in the list.

“`

In the example above, the `find_index()` function takes two parameters: `my_list`, which is the list to search, and `value`, which is the value you want to find in the list. Inside the function, we use the `index()` method of lists to find the index of the `value` in `my_list`. If the `value` is not present in the list, the `index()` method will raise a `ValueError`. We catch this exception using a `try` and `except` block, and in the `except` block, we handle the case where the value is not present in the list and print an appropriate message.

By using a `try` and `except` block, we can handle the scenario where the value is not present in the list and ensure that the function execution continues without raising an error.

Footnotes- Most popular questions asked related to Removing Element from a List 

How do I remove a specific element from a list in Python?

The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.

Find out our Python Training in Top Cities/Countries

IndiaUSAOther Cities/Countries
BangaloreNew YorkUK
HyderabadChicagoLondon
DelhiAtlantaCanada
ChennaiHoustonToronto
MumbaiLos AngelesAustralia
PuneBostonUAE
KolkataMiamiDubai
AhmedabadSan FranciscoPhilippines

How do I remove the first element from a list in Python?

We can do it vie these four options:

  1. list.pop() –
    The simplest approach is to use list’s pop([i]) method which removes and returns an item present at the specified position in the list.
  2. list.remove() –
    This is another approach where the method remove(x) removes the first item from the list which matches the specified value.
  3. Slicing –
    To remove the first item we can use Slicing by obtaining a sublist containing all items of the list except the first one.
  4. The del statement –
    Using Del statement, we can remove an item from a list using its index.The difference compared to pop() method is, that this does not return the removed element.

How do you remove the last element of a list in Python?

The method pop() can be used to remove and return the last value from the list or the given index value. If the index is not given, then the last element is popped out and removed.

How do I remove multiple elements from a list in Python?

Even for this purpose, Del keywords can be used. It will remove multiple elements from a list if we provide an index range. To remove multiple elements from a list in index positions 2 to 5, we should use the del method which will remove elements in range from index2 to index5.

I hope you were able to go through this article and get a fair understanding of the various techniques to Remove Elements from List. 

Make sure you practice as much as possible and revert your experience.  
To get in-depth knowledge on Python Programming language along with its various applications, Enroll now in our comprehensive Python Course and embark on a journey to become a proficient Python programmer. Whether you’re a beginner or looking to expand your coding skills, this course will equip you with the knowledge to tackle real-world projects confidently.

Got a question for us? Please mention it in the comments section of this “Remove Elements from List” blog and we will get back to you as soon as possible.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 22nd June,2024

22nd June

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Python Remove List: How to remove element from Lists

edureka.co