Python lists remove item

Remove an item from a list in Python (clear, pop, remove, del)

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using the del statement by specifying a position or range with an index or slice. Additionally, you can utilize list comprehensions to remove items that meet a specific condition.

To learn how to add an item to a list, see the following article:

Remove all items: clear()

You can remove all items from a list with clear() .

Remove an item by index and get its value: pop()

You can remove the item at the specified position and get its value with pop() . The index starts at 0 (zero-based indexing).

l = [0, 10, 20, 30, 40, 50] popped_item = l.pop(0) print(popped_item) # 0 print(l) # [10, 20, 30, 40, 50] popped_item = l.pop(3) print(popped_item) # 40 print(l) # [10, 20, 30, 50] 

Negative values can be used to specify a position from the end of the list, with the last index being -1 .

popped_item = l.pop(-2) print(popped_item) # 30 print(l) # [10, 20, 50] 

If no argument is provided, the last item in the list is removed.

popped_item = l.pop() print(popped_item) # 50 print(l) # [10, 20] 

Specifying a nonexistent index will result in an error.

# popped_item = l.pop(100) # IndexError: pop index out of range 

Note that using pop(0) to remove the first item is an O(n) operation and is inefficient. For the computational complexity of various operations on lists, see the official Python wiki:

Читайте также:  Wordpress xmlrpc php rsd

To remove the first item with O(1) complexity, use the deque type provided in the standard library’s collections module. For example, when treating data as a queue (FIFO), deque is a more efficient option.

Remove an item by value: remove()

You can remove the first item in the list whose value equals the specified value with remove() .

l = ['Alice', 'Bob', 'Charlie', 'Bob', 'Dave'] l.remove('Alice') print(l) # ['Bob', 'Charlie', 'Bob', 'Dave'] 

If the list contains more than one item with the specified value, only the first occurrence is deleted.

l.remove('Bob') print(l) # ['Charlie', 'Bob', 'Dave'] 

To remove multiple items that meet a specific condition at once, use list comprehensions as described below.

If you specify a nonexistent value, an error will be raised.

# l.remove('xxx') # ValueError: list.remove(x): x not in list 

You can use the in operator to check if a list contains a specific item.

Remove items by index or slice: del

In addition to the list methods, you can remove elements from a list using the del statement.

Specify the item to be deleted by index. The first index is 0 , and the last is -1 .

l = [0, 10, 20, 30, 40, 50] del l[0] print(l) # [10, 20, 30, 40, 50] del l[3] print(l) # [10, 20, 30, 50] del l[-1] print(l) # [10, 20, 30] del l[-2] print(l) # [10, 30] 

You can delete multiple items with slice notation.

l = [0, 10, 20, 30, 40, 50] del l[2:5] print(l) # [0, 10, 50] l = [0, 10, 20, 30, 40, 50] del l[:3] print(l) # [30, 40, 50] l = [0, 10, 20, 30, 40, 50] del l[-2:] print(l) # [0, 10, 20, 30] 

It is also possible to delete all items by specifying the entire range.

l = [0, 10, 20, 30, 40, 50] del l[:] print(l) # [] 

You can specify step as [start:stop:step] .

l = [0, 10, 20, 30, 40, 50] del l[::2] print(l) # [10, 30, 50] 

See the following article for details on slices.

Remove items that meet the condition: List comprehensions

Removing items that satisfy a specific condition is equivalent to extracting items that do not satisfy the condition.

To achieve this, use list comprehensions.

An example of removing odd or even items (i.e., keeping even or odd items) is as follows. % is the remainder operator, and i % 2 calculates the remainder when dividing i by 2 .

When using list comprehensions, a new list is created, leaving the original list unchanged. This is different from using list type methods or the del statement.

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] evens = [i for i in l if i % 2 == 0] print(evens) # [0, 2, 4, 6, 8] odds = [i for i in l if i % 2 != 0] print(odds) # [1, 3, 5, 7, 9] print(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

For details on extracting elements using list comprehensions, see the following article:

Here are other examples of using list comprehensions:

l = ['Alice', 'Bob', 'Charlie', 'Bob', 'David'] print(l) # ['Alice', 'Bob', 'Charlie', 'Bob', 'David'] print([s for s in l if s != 'Bob']) # ['Alice', 'Charlie', 'David'] print([s for s in l if s.endswith('e')]) # ['Alice', 'Charlie'] 

For examples involving a list of strings, see the following article:

To remove duplicate elements from a list, use set() :

print(list(set(l))) # ['Alice', 'Charlie', 'David', 'Bob'] 

Источник

Python List .remove() — How to Remove an Item from a List in Python

Dionysia Lemonaki

Dionysia Lemonaki

Python List .remove() - How to Remove an Item from a List in Python

In this article, you’ll learn how to use Python’s built-in remove() list method.

By the end, you’ll know how to use remove() to remove an item from a list in Python.

Here is what we will cover:

The remove() Method — A Syntax Overview

The remove() method is one of the ways you can remove elements from a list in Python.

The remove() method removes an item from a list by its value and not by its index number.

The general syntax of the remove() method looks like this:

  • list_name is the name of the list you’re working with.
  • remove() is one of Python’s built-in list methods.
  • remove() takes one single required argument. If you do not provide that, you’ll get a TypeError – specifically you’ll get a TypeError: list.remove() takes exactly one argument (0 given) error.
  • value is the specific value of the item that you want to remove from list_name .

The remove() method does not return the value that has been removed but instead just returns None , meaning there is no return value.

If you need to remove an item by its index number and/or for some reason you want to return (save) the value you removed, use the pop() method instead.

How to Remove an Element from a List Using the remove() Method in Python

To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method.

remove() will search the list to find it and remove it.

#original list programming_languages = ["JavaScript", "Python", "Java", "C++"] #print original list print(programming_languages) # remove the value 'JavaScript' from the list programming_languages.remove("JavaScript") #print updated list print(programming_languages) #output #['JavaScript', 'Python', 'Java', 'C++'] #['Python', 'Java', 'C++'] 

If you specify a value that is not contained in the list, then you’ll get an error – specifically the error will be a ValueError :

programming_languages = ["JavaScript", "Python", "Java", "C++"] #I want to remove the value 'React' programming_languages.remove("React") #print list print(programming_languages) #output # line 5, in #programming_languages.remove("React") #ValueError: list.remove(x): x not in list 

To avoid this error from happening, you could first check to see if the value you want to remove is in the list to begin with, using the in keyword.

It will return a Boolean value – True if the item is in the list or False if the value is not in the list.

programming_languages = ["JavaScript", "Python", "Java", "C++"] #check if 'React' is in the 'programming_languages' list print("React" in programming_languages) #output #False 

Another way to avoid this error is to create a condition that essentially says, «If this value is part of the list then delete it. If it doesn’t exist, then show a message that says it is not contained in the list».

programming_languages = ["JavaScript", "Python", "Java", "C++"] if "React" in programming_languages: programming_languages.remove("React") else: print("This value does not exist") #output #This value does not exist 

Now, instead of getting a Python error when you’re trying to delete a certain value that doesn’t exist, you get a message returned, saying the item you wanted to delete is not in the list you’re working with.

The remove() Method Removes the First Occurrence of an Item in a List

A thing to keep in mind when using the remove() method is that it will search for and will remove only the first instance of an item.

This means that if in the list there is more than one instance of the item whose value you have passed as an argument to the method, then only the first occurrence will be removed.

Let’s look at the following example:

programming_languages = ["JavaScript", "Python", "Java", "Python", "C++", "Python"] programming_languages.remove("Python") print(programming_languages) #output #['JavaScript', 'Java', 'Python', 'C++', 'Python'] 

In the example above, the item with the value of Python appeared three times in the list.

When remove() was used, only the first matching instance was removed – the one following the JavaScript value and preceeding the Java value.

The other two occurrences of Python remain in the list.

What happens though when you want to remove all occurrences of an item?

Using remove() alone does not accomplish that, and you may not want to just remove the first instance of the item you specified.

How to Remove All Instances of an Item in A List in Python

One of the ways to remove all occurrences of an item inside a list is to use list comprehension.

List comprehension creates a new list from an existing list, or creates what is called a sublist.

This will not modify your original list, but will instead create a new one that satisfies a condition you set.

#original list programming_languages = ["JavaScript", "Python", "Java", "Python", "C++", "Python"] #sublist created with list comprehension programming_languages_updated = [value for value in programming_languages if value != "Python"] #print original list print(programming_languages) #print new sublist that doesn't contain 'Python' print(programming_languages_updated) #output #['JavaScript', 'Python', 'Java', 'Python', 'C++', 'Python'] #['JavaScript', 'Java', 'C++'] 

In the example above, there is the orginal programming_languages list.

Then, a new list (or sublist) is returned.

The items contained in the sublist have to meet a condition. The condition was that if an item in the original list has a value of Python , it would not be part of the sublist.

Now, if you don’t want to create a new list, but instead want to modify the already existing list in-place, then use the slice assignment combined with list comprehension.

With the slice assignment, you can modify and replace certain parts (or slices) of a list.

To replace the whole list, use the [:] slicing syntax, along with list comprehension.

The list comprehension sets the condition that any item with a value of Python will no longer be a part of the list.

programming_languages = ["JavaScript", "Python", "Java", "Python", "C++", "Python"] programming_languages[:] = (value for value in programming_languages if value != "Python") print(programming_languages) #output #['JavaScript', 'Java', 'C++'] 

Conclusion

And there you have it! You now know how to remove a list item in Python using the remove() method. You also saw some ways of removing all occurrences of an item in a list in Python.

I hope you found this article useful.

To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.

You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.

Thanks for reading and happy coding 😊 !

Источник

Оцените статью