CodeBlessU
learn code with examples

Python Remove by Index, pop

Use .pop() method to remove item by index in mutable sequence (List / Array / String). See How to Remove element by Index from Tuple.

Argument is optional. If index is not specified, it remove last element.

If specified index is out of range, it raises IndexError.

Syntax:
variable.pop(index)
Return Value:
it returns element removed from sequence.
Use
  • Remove - to remove element by value.
  • Pop - to remove element by index.
  • Clear - to remove all elements.

IndexError: pop index out of range

Why this error:

Are you trying to call .pop() with index indicating position that does not exists?

Solution:

Call .pop() with index range 0 to n-1 OR -1 to -n.

List Remove by Index, Pop

List remove element from middle

# Example, List remove element by Index
a1 = [10, 20, 30, 40, 50, 20]

element = a1.pop(2)
print(a1) # [10, 20, 40, 50, 20]
print(element) # 30

List remove last element

# Example, List remove last element
a1 = [10, 20, 30, 40, 50]

element = a1.pop()
print(a1) # [10, 20, 30, 40]
print(element) # 50

List remove first element

# Example, List remove first element
a1 = [10, 20, 30, 40, 50]

element = a1.pop(0)
print(a1) # [20, 30, 40, 50]
print(element) # 10

IndexError: pop index out of range

# Example, List pop raises IndexError
a1 = [10, 20, 30, 40, 50]

a1.pop(15) # raises IndexError: pop index out of range

Tuple Remove by Index

Tuple once created, can not be modified. Alternate approach is to use slicing and concatenation to remove it.
# Example, Remove/delete element by index in tuple
a1 = (10, 20, 30, 40, 50, 100)

# remove element at index 4
a1 = a1[:4] + a1[5:]
print(a1)

Array Remove by Index, Pop

Array remove element from middle

# Example, Array remove element by Index
import array
a1 = array.array('l', [10, 20, 30, 40, 50, 20] )

element = a1.pop(2)
print(a1) # array('l', [10, 20, 40, 50, 20])
print(element) # 30

Array remove last element

# Example, Array remove last element
import array
a1 = array.array('l', [10, 20, 30, 40, 50] )

element = a1.pop()
print(a1) # array('l', [10, 20, 30, 40])
print(element) # 50

Array remove first element

# Example, Array remove first element
import array
a1 = array.array('l', [10, 20, 30, 40, 50] )

element = a1.pop(0)
print(a1) # array('l', [20, 30, 40, 50])
print(element) # 10

IndexError: pop index out of range

# Example, Array pop raises IndexError
import array
a1 = array.array('l', [10, 20, 30, 40, 50] )

a1.pop(15) # raises IndexError: pop index out of range

In this page...

Copyright © All rights reserved.