Remove Elements from List in Python | Delete Items from List

Elements from a list can be removed (deleted) using the remove(element) method in Python.

In the previous article, we learned about accessing list elements by index, using the list index method to find the index of a given element, appending elements to lists and updating list elements.

Remove elements from list

In Python, lists are mutable objects. Mutable object means we can modify the list objects and we can perform operations like add (append), update (change) and delete (remove) on elements in the list. The remove(element) method is used to delete (remove) elements from a list.

remove() method syntax:

list_obj.remove(element)

  • The <class 'list'> has provided the remove(element) method to delete elements from the list. This method takes one parameter, which is the element to be removed from the list.
  • This method is called on the list object from which we want to delete the element.
  • Using this method, the first occurrence of the element will be removed.
  • If the element to be removed is not present in the list, a ValueError will be thrown.
  • remove(element) method will check for case-sensitivity before deleting an element or will throw an error.
  • We can perform this remove operation on the nested list elements as well.

Now, lets see how we can use remove(element) method in programs.

Remove Elements from List in Python - Delete Items from List
Remove Elements from List in Python – Delete Items from List

Program – Remove Elements from List in Python

# remove elements from list in Python - using remove()

shbytes_list = ['Python', 'AWS', 'Java', 'Azure', 'Machine Learning', 'Java']
print(shbytes_list)

shbytes_list.remove('Java')      # Element 'Java' present two times at index 2 and 5
print(shbytes_list)

In this program, we have declared and initialized a list which is referenced by a variable name sybytes_list. First, we print the originally defined list. Then, we call the remove() method on the sybytes_list to remove element Java from this list.

Note – Element Java is present twice (at index 2 and index 5) in the given list. The remove(element) method will only remove the first occurrence of the element.

Output – Example Program – Remove Elements from List in Python

['Python', 'AWS', 'Java', 'Azure', 'Machine Learning', 'Java']
['Python', 'AWS', 'Azure', 'Machine Learning', 'Java']

As you can see, the first occurrence of Java (at index 2) is removed from the list, and the second Java (at index 5) remains.

Program – Remove Element from Nested List in Python

# remove element from nested list in Python

nested_list = ['Python', 'AWS', 'Azure', [1, 2, 3]]
print("original nested list", nested_list)

nested_list[3].remove(2)               # Remove element 2 from the nested element at index 3
print("changed mixed list", nested_list)

We have declared and initialized a nested list which is referenced by a variable name nested_list. Nested element [1, 2, 3] is at index 3 of the list. We access list at index 3 and then called remove() method to delete a index 2 element from nested list [1, 2, 3]. Since nested element is also a list that is why we are able to call remove() method on that element.

Output – Example Program – Remove Element from Nested List in Python

original nested list ['Python', 'AWS', 'Azure', [1, 2, 3]]
changed mixed list ['Python', 'AWS', 'Azure', [1, 3]]

After executing the remove() method, element 2 is successfully deleted from the nested list.

Program – Error: Element not in List

# Error: element not in list

shbytes_list = ['Python', 'AWS', 'Java', 'Azure', 'Machine Learning', 'Java']
print(shbytes_list)

shbytes_list.remove('GoLang')      # Remove element 'GoLang' from the list
print(shbytes_list)

In this program, using remove() method we attempt to delete an element GoLang that is not present in the list. When we try to remove an element that doesn’t exist in the list, it raised a ValueError.

Output – Error: Element not in List

['Python', 'AWS', 'Java', 'Azure', 'Machine Learning', 'Java']

Traceback (most recent call last):
  File "D:-delete-list-elements.py", line 24, in <module>
    shbytes_list.remove('GoLang')
ValueError: list.remove(x): x not in list

As shown, a ValueError is raised because the element GoLang does not exist in the list. ValueError: list.remove(x): x not in list

Program – Error: Case-Sensitive Element Not in List

# Error: Case-Sensitive Element Not in List

shbytes_list = ['Python', 'AWS', 'JAVA', 'Azure', 'Machine Learning']
print(shbytes_list)

shbytes_list.remove('java')
print(shbytes_list)

In this example, we have declared and initialized a list referenced by shbytes_list. This list has element JAVA, which is written in capital-case letters. Using shbytes_list.remove('java'), we are trying to an element java, which is written in small-case letters. remove() method will check for case-sensitivity before deleting an element and will delete an element which are of different case letters. This program will raise a ValueError.

Output – Example Program – Error: Case-Sensitive Element Not in List

['Python', 'AWS', 'JAVA', 'Azure', 'Machine Learning']

Traceback (most recent call last):
  File "D:-delete-list-elements.py", line 23, in <module>
    shbytes_list.remove('java')
ValueError: list.remove(x): x not in list

Exact match of element with case-sensitive letters is not present in the list. remove(element) method raise an error. ValueError: list.remove(x): x not in list

Summary

In this article, we learned how to remove elements from list in Python, using the remove() method. We covered:

  • Remove elements from list in Python.
  • Remove elements from Nested List in Python
  • Dealing with errors when attempting to remove an element not in the list or when the element is case-sensitive.

By understanding the remove() method and handling errors correctly, we can safely and efficiently manage the contents of our Python lists.

Code snippets and programs related to Remove Elements from List in Python, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.

Interview Questions & Answers

Q: What are the differences between remove(), pop(), and del for removing elements in a list?

  • remove(element) – Removes the first occurrence of element from the list. It raises a ValueError if element is not found.
  • pop([index]) – Removes and returns the element at index index. If index is not provided, it removes the last element. Raises an IndexError if the list is empty or if index is out of range.
  • del statementdel can remove elements by index or a slice of elements. It does not return the removed elements and can also be used to delete variables.

Q: How can we remove all occurrences of a specific element from a list?

We can use a list comprehension or a loop to filter out all occurrences of the element. Example to remove elements using a loop.

number_list = [1, 2, 3, 2, 4, 2]
while 2 in number_list:
    number_list.remove(2)
print(number_list)              # Elements remain in number_list: [1, 3, 4]

Q: What happens if we try to remove an element that is not in the list?

  • remove(element) – Raises a ValueError if element is not in the list.
  • pop(index) – Raises an IndexError if the index index is out of range.
  • del statement – Raises an IndexError if the index or slice is out of range.
number_list = [1, 2, 3, 2, 3]
number_list.remove(4)  # Raises ValueError: list.remove(x): x not in list
number_list.pop(5)     # Raises IndexError: pop index out of range
del number_list[5]     # Raises IndexError: list index out of range

Q: When should modify a list in-place versus creating a new list when removing elements?

  • In-Place Modification – When we need to maintain the original list object or when working with large lists to save memory, then we can use in-place modification methods (e.g., remove(), pop(), del). In-place modification is generally done using loop and index position.
  • Creating a New List – When we need to keep the original list unchanged or when performing more complex filtering, then we can create a new list using list comprehension or other methods. Example of creating new list:
original_list = [10, 12, 13, 14, 15]
new_list = [x for x in original_list if x % 2 == 0]
# original_list remains unchanged
print(original_list)  # Elements in original_list: [10, 12, 13, 14, 15]
print(new_list)        # Elements in new_list: [10, 12, 14]

In this example, we are creating a new_list and original_list elements remain unchanged.

Q: How can we remove elements from a list while iterating through the list using enumerate()?

enumerate() method is used to iterate over the copy of a list with indices. We should be careful while iterating over a copy of the list if it is being modified during iteration.

number_list = [10, 12, 13, 14, 15]
for index, value in enumerate(number_list[:]):  # Iterate over a copy
    if value % 2 == 0:
        number_list.remove(value)
print(number_list)  # Final elements in number_list: [13, 15]

In this example, we are iterating over the copy of a list using enumerate() method. We will remove the element if it is divisible by 2.

Q: How does the size of the list affect the performance of removal operations?

  • Time complexity for remove(element) method is O(n) because it has to search through the list.
  • pop(index) has a time complexity of O(1) for the last element but O(n) for other positions because elements need to be shifted.
  • Creating a new list using list comprehension is often more efficient for large lists compared to multiple calls to remove(element) in a loop.

Related Topics

  • Understanding Lists in Python: A Comprehensive Guide
    Lists in Python List is a core datatype in Python. Lists are sequences used to store elements (collection of data). Lists are similar to Arrays but are of dynamic size. It means the size of the list can be increased or decreased as we add or remove elements from the list. Understanding Python Lists: A…
  • How to Create List in Python | Python List Creation Methods Explained
    List is a sequence data type used to store elements (collection of data). Lists are similar to Arrays but have a dynamic size, meaning the list size can increase or decrease as elements are added or removed. A list is a core data type in Python, along with Tuple, Set and Dictionary. Lists in Python…
  • How to Access List Elements by Index in Python (with Example Programs)
    Python list elements are stored based on their index positions and can be accessed by their index positions, which allows to quickly retrieve specific element from the list. Index assignment to list element in Python, is similar to index assigned in Array elements. Understanding how to access list elements by index is crucial for data…
  • Python List Index Method Explained with Examples | Get Element Position in List
    Elements in a Python list are stored based on their index positions. Lists in Python provides an index(arg) method to get the index position of an element within a list. In the previous article How to Access List Elements by Index, we learned how to access a list element using its index position. In this…
  • Append Elements to List – Python | Add Elements with Append Method
    In Python, elements in a list can be added using the append(element) method. This method allows us to add elements to the end of a list easily. In the previous articles, we explored accessing list elements by index and using the list index method to retrieve an element’s position. This article covers appending new elements…

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *