Search code snippets, questions, articles...

Delete items from a list in Python

Here, we are listing down methods and techniques that are used to remove the items from a list in Python.
cars = ['Tesla', 'Ferrari', 'Nexon', 'SUV']

cars.remove('Nexon')
print(cars)

# -> ['Tesla', 'Ferrari', 'SUV']
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

In the above code snippet, we are using the remove() function of the list to delete the item from the list.

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?
0 Comments