Skip to Content

Python – Replace Item in a List

Lists are very flexible as a data structure. Unlike strings that are immutable, lists are mutable in Python. That is, you can make changes to a list after creating it. In this tutorial, we will look at how to replace an item in a Python list with the help of some examples.

replace value in list diagram

There are a number of ways you can replace an item in a list –

  • If you know the index of the item to be replaced, you can directly assign the new value to the list value at that particular index.
  • If you don’t know the index of the item to be replaced,
    • You can loop through the list to find the item to be replaced and replace it with the new value.
    • Or, you can use a list comprehension with a conditional to check for the value to be replaced and replace it accordingly.

Let’s look at some examples of usage of the above-mentioned methods to replace items in a list in Python.

If you know the index of the item to be replaced, the task becomes a straightforward assignment operation. Assign the new element to the index of the item to be replaced in the list.

# create a list 
ls = [1, 2, 3, 4]
# replace 3 with 7 using the index of 3
ls[2] = 7
# display the list
print(ls)

Output:

[1, 2, 7, 4]

Here we knew the index of the item to be replaced (we wanted to replace 3 which was at index 2). The list now has 7 in place of 3.

If you don’t know the index of the value to be replaced, you can iterate over the values of the list and find the element to be replaced and if found, assign the new value to its index.

# create a list 
ls = [1, 2, 3, 4]
# replace 3 with 7
for i in range(len(ls)):
    # check if the item is the item to be replaced
    if ls[i] == 3:
        # replace the value at its index
        ls[i] = 7
# display the list
print(ls)

Output:

[1, 2, 7, 4]

We get the same result as above, 7 in place of 3 in the list.

You can use list comprehension to create a new list with the items replaced. Use a boolean condition to check for the presence of the matching item. Here’s an example.

# create a list 
ls = [1, 2, 3, 4]
# replace 3 with 7
ls = [7 if item == 3 else item for item in ls]
# display the list
print(ls)

Output:

[1, 2, 7, 4]

We get the same result as above, 3 has been replaced by 7 in the resulting list. Note that here we are not exactly replacing the value in the original list rather we are creating a new list with the values replaced and assigning it to the original list.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush

    Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.