Python remove object from list

How to remove an object from a list in Python?

To remove items (elements) from a list in Python, use the list functions clear(), pop(), and remove(). You can also delete items with the del statement by specifying a position or range with an index or slice.

In this article, we will show you how to remove an object/element from a list using python. The following are the 4 different methods to accomplish this task −

  • Using remove() method
  • Using del keyword
  • Using pop() method
  • Using clear() method

Assume we have taken a list containing some elements. We will return a resultant list after removing the given item from an input list using different methods as specified above.

Method 1: Using remove() method

The remove() function deletes the given item passed as an argument to it. −

Syntax

list.remove(element) Return Value:The remove() function will not return any value(returns None)

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task

  • Create a variable to store the input list.
  • Use the remove() method to remove the particular item from the input list by passing the list item to be deleted as an argument to it and applying it to the input list.
  • Print the result list after removing the specified item from the input list
Читайте также:  Var что такое питоне

Example

The following program removes the specified item from an input list using the remove() method and prints the resultant list −

# input list inputList = ['TutorialsPoint', 'Python', 'Codes', 'hello', 'everyone'] # Removing the 'TutorialsPoint' from the list using the remove() method inputList.remove("TutorialsPoint") # Printing the result list print("Input List after removing :\n", inputList)

Output

On executing, the above program will generate the following output −

Input List after removing : ['Python', 'Codes', 'hello', 'everyone']

As an input to the code, we were given a sample list with some random values, as well as an object/element to remove from the list. The element was then passed to the remove() method, where it was deleted/removed from the list. If the object/element is not found in the list, a value error will be returned.

Method 2: Using del Keyword

The del statement is not a List function. The del statement can be used to delete items from the list by passing the index of the item (element) to be deleted

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input list.
  • Use the del keyword, to remove the item present at the specified index (here 2nd index(Codes)) from the list.
  • Print the resultant list i,e after removing the specified item from the list.

Example

The following program removes the specified item from an input list using the del keyword and prints the resultant list −

# input list inputList = ['TutorialsPoint', 'Python', 'Codes', 'hello', 'everyone'] # Removing the item present at the 2nd index(Codes) from the list del inputList[2] # Printing the result list print("Input List after removing the item present at the 2nd index:\n", inputList)

Output

On executing, the above program will generate the following output −

Input List after removing the item present at the 2nd index: ['TutorialsPoint', 'Python', 'hello', 'everyone']

Method 3: Using pop() method

With pop() method, you can delete the element at the specified position and retrieve its value.

The starting value of the index is 0 (zero-based indexing).

If no index is specified, the pop() method removes the last element from the list.

Negative values can be used to represent the position from the end. The last index is -1.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input list.
  • Use the pop() method, bypassing the index of a list item as an argument the to it to remove the item at the given index
  • Pass the negative index values as an argument to the pop() method, to remove the list items from the last. Here for removing the last item from the list we passed the -1 index as an argument to the pop() method.
  • Print the resultant list i,e after removing the specified item from the list.

Example

The following program removes the specified item from an input list using the pop() method and prints the resultant list −

# input list inputList = ['TutorialsPoint', 'Python', 'Codes', 'hello', 'everyone'] # Removing the 'TutorialsPoint' from the list using the pop() method del_item = inputList.pop(0) # Removing the 'everyone' from the list by passing the negative index -1 last_del_item = inputList.pop(-1) # Printing the result list print("Input List after removing , :\n", inputList)

Output

Input List after removing , : ['Python', 'Codes', 'hello']

Method 4: Using clear() method

The clear() method removes all items from the list. The list is still there, but it is empty.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input list.
  • Use the clear() method, to remove all the items from the list.
  • Print the resultant list i,e after removing all the from the list.

Example

The following program clears or empties the complete list using the clear() function −

# input list inputList = ['TutorialsPoint', 'Python', 'Codes', 'hello', 'everyone'] # Removing all the items from the list inputList.clear() # Printing the result list print("Input List after removing all the items:", inputList)

Output

Input List after removing all the items: []

Conclusion

We learned how to remove an object/element from a list using four different methods in this article: remove(), pop(), clear(), and the del keyword. We also learned about the errors that those methods generate if the element is not in the list.

Источник

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:

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'] 

Источник

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