Python’s List Method - replace() and the index argument

The ‘replace()’ method replaces all occurrences of a specified value with another value. But sometimes, you may want to replace only the element at a specific index. In this case, you can use the inde …

Updated October 16, 2023

The ‘replace()’ method replaces all occurrences of a specified value with another value. But sometimes, you may want to replace only the element at a specific index. In this case, you can use the index argument in Python’s list methods.

Replace an Element at Specific Index

To replace an element at a specific index in Python, we have two ways, either by using ‘insert()’ method to remove and insert again or by directly replacing it. Below are both ways of doing this task:

Using the insert() Method Suppose you want to replace the 3rd element of a list with another value. You can first remove that element then insert the new one at the same index.

list = [1,2,3,4,5] # let's say this is your list
new_element = 'New'  #let's say you want to replace with new_element
index = 2   #the index of element that we want to replace
# removing the old value
del(list[index])
# inserting the new value at same index
list.insert(index,new_element)

Direct Replacement Using List Index If you want to directly replace an item in a list using its index, then you can use the ‘replace()’ method:

lst = [1, 2, 3, 4, 5] # your list
old_value = 3         # value that you want to replace
new_value = 9        # new value that you want to set at the index
index = lst.index(old_value)    # get index of old_value in list
lst[index] = new_value   # replacing old_value with new_value at same index

In both methods, ‘list’ is a mutable sequence data type that holds an ordered collection of items. This allows changes to the list. The ‘replace()’ method replaces all occurrences of a specified value with another value in the given list. If the index is not specified, it replaces all instances of the old element in the list.

For instance, in case you have multiple elements which are similar but differ at some indices or you want to replace an item without knowing its exact index then ‘replace()’ method can be handy as it directly replaces the item with given value and if there is no item matching with old_value then it will return error. But remember that both methods modify the original list.

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!