Search code snippets, questions, articles...

Remove an item from python list using its index

Have you ever wanted to remove an item from a list in Python but weren't sure how? In this code snippet, We will show you one of the easiest and most effective ways to remove an item from a Python list.
fruits = ["Apple", "Banana", "Orange", "Papaya"]

# Remove Orange from the list
del fruits[2]

print(fruits)
# ['Apple', 'Banana', 'Papaya']
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

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.

Remove the last element from the list python

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]
Was this helpful?
0 Comments