Replacing items in a list using Python

This tutorial will show you how to replace certain values, strings or numbers in a given list. You can use the built-in function replace() for string or the map function for other data types in python.

Updated November 24, 2023

This tutorial will show you how to replace certain values, strings or numbers in a given list.

# List of items
list_items = ['apple', 'banana', 'cherry', 1, 2, 3]

# Element to replace
element_to_replace = 'cherry'

# New element
new_element = 'mango'

# Replacing in a list
list_items = [i if i != element_to_replace else new_element for i in list_items]
print(list_items)  # ['apple', 'banana', 'mango', 1, 2, 3]

The map function can be used when you want to replace multiple elements:

# List of items
list_items = ['apple', 'banana', 'cherry', 1, 2, 3]

# Elements to replace (can be any data type)
elements_to_replace = ['apple', 1]

# New elements
new_elements = ['mango', 4]

# Replacing in a list
list_items = list(map(lambda x: new_elements[elements_to_replace.index(x)] if x in elements_to_replace else x, list_items))
print(list_items)  # ['mango', 'banana', 'cherry', 4, 2, 3]

In both examples above, we replace the elements 'apple' and 1 in our original list with 'mango' and 4 respectively. The function index() is used to get the index of a value in another list. If the value isn’t found in the new list (i.e., if it doesn’t have an index), index() throws a ValueError. In that case, we return the original value.

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!