fruits = ["Apple", "Banana", "Orange", "Papaya"]
# Remove Orange from the list
del fruits[2]
print(fruits)
# ['Apple', 'Banana', 'Papaya']
You can use the del keyword to delete an item from a list as shown in the above code example.
1. First, we created a list named fruits and it contains multiple fruit names.
2. We want to remove a fruit name(Orange). It has an index of 2.
3. We are using the del keyword with the list name and passing the index of the item that needs to be removed from the list.
4. Print the list where the removed item(Orange) will not be present.
We know that the index of the last element of a list is considered as -1. Therefore, if we want to remove the last item we can use the below python code.
fruits = ["Apple", "Banana", "Orange", "Papaya"]
# Remove the last element from the above list
del fruits[-1]
print(fruits)
# -> ['Apple', 'Banana', 'Orange']
Also, you can use the pop() function to remove the last element of a list. Below is the example.
nums = [3, 5, 6, 9]
nums.pop()
print(nums)
# -> [3, 5, 6]
0 Comments