How to Remove item at specific index from Python List?

Python – Remove item at specific index from List – pop()

To remove an item at specified index or position from a List, you can use pop() method of List class with index provided as argument.

In this tutorial, we shall play with the pop() function and the indexes, in different approaches. Our ultimate goal it to remove an item from the given position.

Syntax – list.pop()

The syntax of pop() method is:

mylist.pop(index)

where index is optional.

If you do not provide any index, the last item of the list is removed from the list.

Example 1: Remove Item at Specific Index from List

In the following example, we have a list with numbers. We will use pop() method to delete or remove the item at specified indexm, 3.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52]
index = 3

#delete item in mylist at index
mylist.pop(index)

print(mylist)
Run

Output

[21, 5, 8, 21, 87, 52]

The item present at index=3, 52, is removed from the list.

Example 2: Remove Last Item of List

To remove the last item of the list, just don’t pass any index to the pop() method.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52]

#delete last item in mylist
mylist.pop()

print(mylist)
Run

Output

[21, 5, 8, 52, 21, 87]

Example 3: pop() with index > List length

If you provide an index greater than the length of the list, you will get IndexError with the message pop index out of range.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52]
index = 100 #index > length of list

mylist.pop(index)

print(mylist)
Run

Output

Traceback (most recent call last):
  File "example.py", line 5, in <module>
    mylist.pop(index)
IndexError: pop index out of range

Example 4: pop() with negative index

If you provide a negative index to the pop() method, the indexing is considered from the last item of the list starting from 1.

If you give -1 as index to pop(), the last item of the list is deleted.

If you give -3 as index to pop(), 3rd item from the end of the list is deleted.

If the absolute of negative index crosses the length of the list, you will get IndexError as in previous example.

In the following example, we will provide -2 as index to the pop() method. The second item from last of the list is deleted.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52]
index = -2 #index < 0

mylist.pop(index)

print(mylist)
Run

Output

[21, 5, 8, 52, 21, 52]

Summary

In this tutorial of Python Examples, we learned how to use pop() function, to remove or delete an item from a given position in the list.