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,
print(my_list) # ["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:
- Convert List from Character String to Float in Python (3 Examples)
- Loop Through List of Strings in Python (3 Examples)
- How to Use Lists in Python (13 Examples)
- Python Programming Language for Statistics & Data Science
- Append Boolean to List in Python (4 Examples)
Now you have the knowledge and techniques to replace a string value in a list with another value in Python. Happy coding!
Statistics Globe Newsletter