python

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.

Remove an item from a list using its index in Python

To remove an item from a list using item index in Python:

  1. Create a List that contains items - fruits = ["Apple", "Banana", "Orange", "Papaya"].
  2. Remove the item using the del keyword and item index - del fruits[2]. This will remove the third item(Orange) from the list.

Remove an item from the List using the del keyword

The del keyword is a powerful tool in Python that can be used to remove an item from a list. This keyword can be used to delete an item from a list by its index, or by its value.

The following example will explain how to use the del keyword to remove an item from a list.

fruits = ["Apple", "Banana", "Orange", "Papaya"]

# Remove Orange from the list
del fruits[2]

print(fruits) # Output - ['Apple', 'Banana', 'Papaya']

The above code example removes the item "Orange" from the list of fruits. The del command is used to delete items from a list.

The number 2 in the del command is the index of the item "Orange" in the list. After the del command is executed, the list is printed, which shows that "Orange" has been removed from the list. The output shows the list with only the items "Apple", "Banana" and "Papaya".


Remove item from the list using pop() function

Also, you can use the pop() function to remove the last element of a list. Below is an example. You need to pass the index of the item to delete it. For example if there is a list of numbers and you want to delete the second element from the list, you can use the below code example:

nums = [3, 5, 6, 9]

nums.pop(1)

print(nums) # Output - [3, 6, 9]

If you have not passed any index to the pop() function it will remove the last item from the list.

nums = [3, 5, 6, 9]

nums.pop()

print(nums) # Output -> [3, 5, 6]

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