Replace String in List in Python (Example)

In this tutorial, you’ll learn how to replace a string value in a list with another value in Python. This can be useful when you want to modify specific elements in a list based on their string values. We’ll explore different examples to demonstrate this process.

The table of contents is structured as follows:

Let’s get started!

Initializing a Sample List

Firstly, let’s initialize a sample list that contains string values:

# Initializing a sample list
my_list = ["apple", "banana", "cherry", "date", "elderberry"]

This creates a list, my_list, which contains string values.

Example: Replacing a String Value in a List

To replace a string value in the list, we can iterate over each element and use conditional statements to identify the string value we want to replace. Here’s an example where we replace the value "cherry" with "grape":

# Replace "cherry" with "grape"
for i in range(len(my_list)):
    if my_list[i] == "cherry":
        my_list[i] = "grape"

In this example, we use a for loop to iterate over each element in the list. Inside the loop, we check if the element is equal to "cherry". If it is, we replace it with "grape".

After executing this code, the updated list will be the following,

# ["apple", "banana", "grape", "date", "elderberry"]

As you can see, the string value "cherry" has been replaced with "grape" in the list.

Video, Further Resources & Summary

In this tutorial, we explored an example of how to replace a string value in a list with another value in Python. By iterating over the list and using conditional statements, we can modify specific elements based on their string values.

Do you need more explanations on looping through a list of integers in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

The YouTube video will be added soon.

For more Python programming tutorials and examples, you can check out the following resources on Statistics Globe:

Now you have the knowledge and techniques to replace a string value in a list with another value in Python. Happy coding!

Ömer Ekiz Python Programming & Informatics
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.