CodeBlessU
learn code with examples

Python Replace element

You need two things to replace or update element in mutable sequence (List / Array / String)
  • index position - where to replace
  • element value / replacement item - replace with what?

Use assignment operation with index to replace element in sequence.

Syntax:
variable[index] = put new value
Return Value:
no return value
Use
  • Replace/Update - to update value at existing position.
  • Append - to add new element at end (Single).
  • Extend - to add new elements at end from iterable source (Single / Multiple).
  • Insert - to insert new element at start / middle (Single).

IndexError: assignment index out of range

Why this error:

Are you trying to assign value at index which does not exists, i.e. outside its range?

Solution:

To replace / update element, the index must be within 0 to n-1 or -1 to -n.

Are you trying to append new element?

List replace element

# Example, list replace element, list update element
a1 = [10, 20, 29, 40, 50]

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

IndexError: list assignment index out of range

# Example, list update raises IndexError
a1 = [10, 20, 30, 40, 50]

a1[8] = 80 # raises IndexError: list assignment index out of range

Tuple replace element

Tuple once created, can not be modified. But, two tuple can be added/concatenated to create another tuple. Use + operator to concatenate tuples.

Open Thoughts: Are you finding frequent need to replace element in tuple? Would it be helpful to change its data type?

# Example, tuple replace element
a1 = (10, 20, 29, 40, 50)

a1 = a1[:2] + (30,) + a1[3:]
print(a1) # (10, 20, 30, 40, 50)

Array replace element

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

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

TypeError: append() takes exactly one argument

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

a1[8] = 80 # raises IndexError: array assignment index out of range

In this page...

Copyright © All rights reserved.