To delete an item from a List in Python:
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.
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]
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
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
0 Comments