Python delete all items in 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.

Читайте также:  Python module source file

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:

Читайте также:  Html background image black

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

Источник

Delete All Elements Of A List In Python

In python, we use lists in almost every program. We have already discussed ways to compare two lists and to reverse a list in python. In this article, we will discuss different ways to delete all the elements of a list in python.

Delete All Elements Of A List In Python Using The clear() Method

The pop() method is used to delete the last element of a list. When invoked on a list, the pop() method returns the last element of the list and deletes it from the list. We can use the while loop and the pop() method to remove all the elements of the list.

For this, we can keep invoking the pop() method on the list inside the while loop until the list becomes empty. Once the list becomes empty, the while loop will stop its execution and we will get a list that has no elements. You can observe this in the following program.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] print("The original list is:") print(myList) # deleting elements using the pop() method while myList: myList.pop() print("List after deleting all the elements:",myList)
The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9] List after deleting all the elements: []

Instead of using the pop() method several times, we can use the clear() method to delete all the elements from a list. The clear() method, when invoked on a list, deletes all the elements of the list.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] print("The original list is:") print(myList) # deleting elements using the clear() method myList.clear() print("List after deleting all the elements:",myList)
The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9] List after deleting all the elements: []

Delete All Elements Of A List In Python Using The del Statement

The del statement is used to delete an object in python. We can also use the del statement to remove the elements of a list. For this, we will create a slice of the list that contains all the elements. After that, we will delete the slice. As the slice contains references to the elements in the original list, all the elements in the original list will be deleted and we will get an empty list. You can do it as follows.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] print("The original list is:") print(myList) # deleting elements using the del method del myList[:] print("List after deleting all the elements:", myList)
The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9] List after deleting all the elements: []

Delete All Elements Of A List In Python Using The * Operator

This is one of the least used ways to remove elements from a list in Python. You might be knowing that multiplying a list to any number N repeats the elements of the list N times. In the same way, when we multiply a list to 0, all the elements of the list are deleted. So, we can multiply the given list with 0 to remove all of its elements as follows.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] print("The original list is:") print(myList) # deleting elements using * myList = myList * 0 print("List after deleting all the elements:", myList) 
The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9] List after deleting all the elements: []

Conclusion

In this article, we have discussed four different ways to delete all the elements of a list in python. To know more about lists in python, you can read this article on list comprehension. You might also like this article on how to get the last element of a list in python.

Читайте также:  Замыкание функции javascript это

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Источник

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