Thursday, March 28, 2024
HomeEducationHow to Remove an Item From List Python 

How to Remove an Item From List Python 

Remove Item From List Python

Python is one of the most popular programming languages in today’s market. We can use Python for Machine Learning, Artificial Intelligence, Data Mining, Data Analysis, Software Development, Web Development, etc. The reason behind that is the array of functionalities Python offers. One of the functionalities is a List that helps programmers to a great extent. Today we will learn about how we can remove item from List Python.

But before moving on, let’s learn about what lists are and why we use them.

What are Lists?

Lists are collections of elements that are ordered and changeable and hold a variety of data objects. Lists can also store duplicate elements. We can compare Python Lists with arrays in other programming languages, but the main difference is that in an array, the same data types elements are stored, whereas, in lists, different data types elements can be stored. A single list can have data types like string, integer, floating-point number, etc. Lists are mutable, which means we can alter them after creation, and also, we can perform slicing and indexing on lists the same as we do on a string. A list can be nested. That is, we can create a list within a list.

Lists are very useful in stack and queue in Python. All the elements in the list are enclosed in square brackets, and each element is separated by a comma.

Example:

my_list = [1, “Hello”, 3.4, 6, 9, “Great Learning”, 33, 9.2]
print (my_list)

Output:

[1, “Hello”, 3.4, 6, 9, “Great Learning”, 33, 9.2]

Why use Lists?

There may be some situations where we need to handle different types of data at the same time, which is impossible in other programming languages such as C, C++, and Java, where we can store similar types of data in an array. 

This is where Lists in Python play an important role. We can store different types of data in a single ordered collection. So, that’s why lists play an important role.

Now let’s see how we can remove elements from Python Lists.

Syntax of List remove()

The remove() method is one of the ways of removing the elements from the Python list. The remove() method removes the element from the lists by its value, not by its index number. 

The general syntax of remove() method is:

list_name.remove (value)

Parameters of remove()

  • list_name: It refers to the name of the list from where we want to remove the element.
  • remove(): remove() is a python built-in function that is used to remove elements from the list. It takes only a single argument as input, if we don’t provide that then it will throw “TypeError”.
  • value: It is the specific value that we want to remove from the list_name.

Example:

languages = [“English”, “Hindi”, “Urdu”, “Sanskrit”]
print (languages) # original list
languages.remove(“English”)
print (languages) # list after removing English 

Output

[“English”, “Hindi”, “Urdu”, “Sanskrit”]

[“Hindi”, “Urdu”, “Sanskrit”]

How to Return value from remove()

The remove() method does not return any value that has been removed, it just returns None, that means there is no return value.

remove() method on a list having duplicate elements

The remove() method will remove only the first occurrence of an item. That means if the same items are present multiple times in a list, that remove() method will only remove the first occurrence of that item.

Example:

color = [ “Red”, “Blue”, “Green”, “Yellow”, “Red”, “Black”, “Orange” ]
color.remove( “Red” )
print( color )

Output

[“Blue”, “Green”, “Yellow”, “Red”, “Black”, “Orange” ]

If you want to remove all the occurrences of an item from a list, then we can make use of list comprehension. List comprehension helps to create a new list from the existing list, or we can call it a sublist.

It will not make any changes to our original list but create a new list that satisfies the particular conditions.

Example:

color_original = [ “Red”, “Blue”, “Green”, “Yellow”, “Red”, “Black”, “Orange” ]
color_new = [ item for item in color_original if item != “Red” ]
print(color_original) # original list
print(color_new) # updated list

Output

[ “Red”, “Blue”, “Green”, “Yellow”, “Red”, “Black”, “Orange” ]

[ “Blue”, “Green”, “Yellow”, “Black”, “Orange” ]

Deleting an element that doesn’t exist

When we use the remove() method to delete an element that is not present in the list, we get “ValueError” as an output. That means it refers to a particular element not present in the defined list.

Example: 

>>> color = ["Red", "Yellow", "Green", "Red", "Blue", "Black"]
>>> color.remove("Orange")
Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> color.remove("Orange")
ValueError: list.remove(x): x not in list
>>>

Different methods of removing an element from the list

Apart from the remove() method, there are some more methods to delete elements from the lists. Let’s see them one by one with examples.

Remove item from list by Index

The pop() method is another method to remove elements from the lists. It performs the same tasks as the remove() method, but the only difference is that the remove() method takes the value as an argument, and the pop() method accepts the index as an argument. We need to give an index as an argument, and the pop() method will pop out the value present at that particular index. The pop() method returns the value present at that index.

Example:

>>> color = ["Red", "Yellow", "Green", "Red", "Blue", "Black"]
>>> color.pop(4)
>>> print(color)

Output:

‘Blue’

 [‘Red’, ‘Yellow’, ‘Green’, ‘Red’, ‘Black’]

In above example the pop() method delete the elements present at index 4 and returns the value present on that index that is ‘Blue’

The pop() method raises “IndexError” if the index specified is out of range.

Remove item from list using del

The del operator is similar to the pop() method with one important difference. The del method takes the index as an argument and removes that element from the list but does not return any value. But the pop() method returns the value present at that index. Similar to the pop() method, del also raises “IndexError” if the index or the indices specified are out of range.

Example:

>>> color = ["Red", "Yellow", "Green", "Red", "Blue", "Black"]
>>> del color[5]
>>> print(color)

Output

[‘Red’, ‘Yellow’, ‘Green’, ‘Red’, ‘Blue’]

How to clear the list

If we want to delete the entire elements from the lists then del would be a preferred method to delete the entire elements from the lists in a single command.

Example:

>>> color = ["Red", "Yellow", "Green", "Red", "Blue", "Black"]
>>> del color[:]
>>> print(color)

Output

[]

In the above example we have given a slicing symbol “:” that means we are defining to delete elements from index 0 to the last index present in the list. This is one of the fastest methods for deleting the elements from the lists.

Conclusion 

So, we have three methods remove(), pop(), and del method, to remove the elements from the python lists. To recall them again, the remove() method takes the value as an argument and removes the first matching value from the list, and does not return any value. The pop() method takes an argument as input and deletes the value present at that index and returns it, and finally, the del operator takes the index or range of indices as input and deletes the element present on those indexes, but the removed item is not returned. 

Frequently Asked Questions

  • How do I remove something from a list in Python?

We can remove any element from the lists by three methods that are remove(), pop() and del. Based on our requirements we can make use of any one of them.

  • What is remove () in Python?

The remove() method removes the element from the lists by its value not by its index number

  • How do I remove a specific index from a list in Python?

To remove the specific index from the list we can use pop() or del method to remove them. The pop() method will remove and return the value present on that index and the del method will only remove that element from that index without returning anything.

  • How do I remove a string from a list in Python?

To remove a string from a list we can use the remove() method. We can pass string as an argument and remove() method will remove the item from the list

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

To remove the last element from the list we can use the pop() method, it will remove and return the last value. If no argument is given the pop() method will remove the last element from the list.

Source: GreatLearning Blog

RELATED ARTICLES
- Advertisment -

Most Popular

Recent Comments