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


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 of 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.

Examples

1. Remove item at index=3 from the list

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

Python Program

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

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

print(mylist)

Output

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

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

2. Remove last item from the 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)

Output

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

3. list.pop(index) where 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)

Output

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

4. list.pop(index) where index is negative

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)

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.