python

Delete items from a list in Python

Python provides several ways to delete items from a list. The most straightforward way is to use the del statement, which allows you to delete an item at a specific index in the list. You can also use the remove() method or the pop() method to delete items from a list. Each of these methods can be used to delete items from a list, depending on your specific needs.

Delete an item from a List in Python

To delete an item from a List in Python:

  1. First, create a List my_list = [2, 4, 6, 8, 10].
  2. Remove an item using the del keyword - del my_list[2]. The output will be  [2, 4, 8, 10].

Delete item using List.remove() function

List.remove() function takes item value as a parameter that needs to be removed from the list. To use this function you need the item value and pass it to the remove function.

Syntax

List.remove(item)

Code example

numbers = [20, 50, 30, 90, 40]

numbers.remove(30)
print(numbers)

Output

[20, 50, 90, 40]

remove() function removes the very first occurrence of the item from the list. It means if you have two items with the same value then it will delete the lowest index element from the list.


Use pop() function - remove item using index

If you know the index of the item that needs to be removed from the list, you can use the pop() function in python. It takes the index of the item as a parameter and removes that element from the list.

Syntax

List.pop(index)

Code Example

companies = ['Microsoft', 'Cisco', 'Google', 'Apple']

companies.pop(1)

print(companies)

Output

['Microsoft', 'Google', 'Apple']

Remove the last element from the list using the pop() function

num_list = [4, 1, 5, 6, 9]

num_list.pop()

print(num_list)

Output

[4, 1, 5, 6]

Use the del keyword to remove the item from the list

You can also use the del keyword to remove the item from the list using the item index. All you need to do is write the del keyword before the list variable name with its index.

Syntax

del List[index]

Code example

num_list = [4, 1, 5, 6, 9]

del num_list[3]

print(num_list)

Output

[4, 1, 5, 9]

We have removed the item that has index 3 from the list using the above code snippet.

Delete the whole list using the del keyword

fruits = ['Apple', 'Mango', 'Orange']

del fruits

Delete all items from the list using the clear() function

If you want to remove all the elements from the list, then you can use List.clear() function in your python code.

Syntax

List.clear()

Code Example

fruits = ['Apple', 'Mango', 'Orange']

fruits.clear()

print(fruits)

Output

[]

Read more about removing items for a list

Remove dictionary for a list in Python

Was this helpful?