In this Python tutorial, we will explore how to replace items in a Python list with several different ways and demonstrative examples.
Before diving into replacing items, let’s quickly recap how to create a list in Python. A list is defined by including a comma-separated sequence of items in square brackets []. For instance:
usa_cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
In this example, usa_cities is a list that contains the names of five U.S. cities. What if we want to replace some items on this list with some other items?
Replacing items in a Python list
There are many different ways to replace items from a list in Python. They are:
- Direct Assignment using Indexing
- Using List Comprehension
- Using list slicing
- For loop
- While loop
- Using map() function
We will see them one by one using illustrative examples.
Method-1: Replace items in a Python list using Indexing
The simplest way to replace an item in a Python list is by direct assignment. Lists in Python are mutable, meaning that we can change their content without changing their identity. We can access an item in a list by referring to its index number. The positive index numbers of a list start from zero for the first element.
Let’s say we want to replace “Chicago” with “San Francisco” in our usa_cities list. “Chicago” is at index 2, so we can replace it as follows:
usa_cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
usa_cities[2] = "San Francisco"
print(usa_cities)
The output is: After running this code, our list becomes:
['New York', 'Los Angeles', 'San Francisco', 'Houston', 'Phoenix']
This way we can use Indexing for direct assignment to replace items in a Python list.
Method-2: Replace items in a Python list using List comprehension
List comprehension in Python is a compact way of creating lists while also performing operations on list items. To replace items in a Python list using list comprehension, we could use a conditional statement within the list comprehension.
let’s use a list of major US cities and If we wanted to replace ‘Houston’ with ‘Philadelphia’, we could use a list comprehension like this:
cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']
cities = ['Philadelphia' if city == 'Houston' else city for city in cities]
print(cities)
The output is:
['New York', 'Los Angeles', 'Chicago', 'Philadelphia', 'Phoenix']
This way we can use List comprehension in Python to replace items in a list.
Method-3: Replace items in a list of Python using List slicing
Another way to replace multiple items is by using list slicing in Python.
So, let’s consider a list of the top 5 U.S. states by area. We’ll try to replace ‘California’, ‘Montana’, and ‘New Mexico’ with ‘Arizona’, ‘Nevada’, and ‘Colorado’ respectively:
states = ['Alaska', 'Texas', 'California', 'Montana', 'New Mexico']
states[2:5] = ['Arizona', 'Nevada', 'Colorado']
print(states)
The output: In Python, list slicing can be used to replace several elements at once. Here we’re replacing the items from index 2 up to but not including index 5 with a new set of items.
['Alaska', 'Texas', 'Arizona', 'Nevada', 'Colorado']
This way we can use list slicing to replace items in a Python list.
Method-4: Replace items in a Python list using for loop
In some cases, we might want to replace multiple items of a certain value in our Python list. To do this, we can use a for-loop to iterate over the list.
Consider a list of American fast-food chains. We’ll try to replace all occurrences of ‘McDonald’s’ with ‘Burger King’ using for loop:
fast_food_chains = ["McDonald's", "Subway", "Starbucks", "Taco Bell", "McDonald's"]
for i in range(len(fast_food_chains)):
if fast_food_chains[i] == "McDonald's":
fast_food_chains[i] = 'Burger King'
print(fast_food_chains)
The output is: In this example, we’re iterating over the list by index, and replacing ”McDonald’s” with ‘Burger King’ each time it’s found.
['Burger King', 'Subway', 'Starbucks', 'Taco Bell', 'Burger King']
This way we can use For loop to replace items from a List in Python.
Method-5: Replace items from a list in Python using while loop
While loop in Python does the same work as for loop. In the while loop first, we define a variable with value 0 and iterate over the list. If the value matches the value that we want to replace. Then we replace it with the new value.
For example: Here we’ll use a list of popular American car brands and try to replace ‘Ford’ with ‘Dodge’.
car_brands = ['Ford', 'Chevrolet', 'Tesla', 'Ford', 'Jeep', 'Cadillac', 'Ford']
i = 0
while i < len(car_brands):
if car_brands[i] == 'Ford':
car_brands[i] = 'Dodge'
i += 1
print(car_brands)
The output is: We’re iterating through the list using a while loop and a counter variable. Each time ‘Ford’ is found, it’s replaced with ‘Dodge’.
['Dodge', 'Chevrolet', 'Tesla', 'Dodge', 'Jeep', 'Cadillac', 'Dodge']
This way we can use while loop to replace items in a Python list.
Method-6: Replace items in a Python list using map() Function
The map() function applies a given function to each item of an iterable (like a list) and returns a list of the results. We can use it in combination with a lambda function to replace items.
For example, Consider a list of US national parks. We’ll try to replace all occurrences of ‘Yosemite’ with ‘Zion’:
parks = ['Yellowstone', 'Yosemite', 'Grand Canyon', 'Sequoia', 'Yosemite']
parks = list(map(lambda park: 'Zion' if park == 'Yosemite' else park, parks))
print(parks)
The output is: The map() function applies a given function to each item of an iterable. In this case, it applies the lambda function, which replaces ‘Yosemite’ with ‘Zion’ for each park in the list.
['Yellowstone', 'Zion', 'Grand Canyon', 'Sequoia', 'Zion']
This way we can use the map() function with the lambda function to replace items in a Python list.
Conclusion:
Throughout this tutorial, we’ve explored 6 different ways to replace items in a Python list. The Indexing, List Comprehension, List Slicing, For loop, While loop, and map() function each with its strengths and use cases. Understanding how and when to use these different methods to replace items in a list is an important part.
You may also like to read:
- How to get the last element in the Python list
- How to remove the first element from a list in Python
- How to add a string to a list in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.