You need to re-assign to li each time, kind of recursive replacement. Because for now you always go from original li to t with a different replacement letter

li = 'Text 1. Text 2? Text 3!'
i = ['.', '?', '!']
for y in i:
    li = li.replace(y, '')

You can also use regex module re and pattern [.?!]

li = 'Text 1. Text 2? Text 3!'
i = ['.', '?', '!']
li = re.sub("[" + "".join(i) + "]", '', li)
Answer from azro on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-replace-values-in-a-list-in-python
Replace Values in a List in Python - GeeksforGeeks
This method walks through the list using index positions and replaces values whenever the specified condition is met during iteration with the help of for loop.
Published ย  January 12, 2026
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ how to replace values in a list in python?
How to Replace Values in a List in Python? - Analytics Vidhya
April 23, 2025 - This method allows you to iterate through each element in the list and check if it meets certain conditions. If the condition is satisfied, you can replace the value with a new one.
Discussions

python - Finding and replacing elements in a list - Stack Overflow
Has one significant problem: It ... or 1.0, kaboom; I prefer kxr's approach for bulletproofing. 2021-02-27T02:07:58.367Z+00:00 ... In many cases, defining a replacer function and calling it in a loop is very readable. It's very useful if values need to be replaced using some ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
string - Is there a method like .replace() for list in python? - Stack Overflow
i've made a list out of a string using .split() method. For example: string = " I like chicken" i will use .split() to make a list of words in the string ['I','like','chicken'] Now if i want to re... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Change values in a list using a for loop (python) - Stack Overflow
I currently have some code that reads like this: letters = { 10 : "A", 11 : "B", 12 : "C", 13 : "D", 14 : "E", 15 : "F" } vallist = [rd1, rd2, gd1, gd2, bd1, bd2] for i in vallist: if i >= ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Curious about logic behind replacing elements of a list.
The idiomatic way to do this would be using enumerate: for i, value in enumerate(some_list): if value == 1: some_list[i] = 2 More on reddit.com
๐ŸŒ r/learnpython
14
4
February 20, 2025
๐ŸŒ
datagy
datagy.io โ€บ home โ€บ python posts โ€บ python: replace item in list (6 different ways)
Python: Replace Item in List (6 Different Ways) โ€ข datagy
August 12, 2022 - One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.
๐ŸŒ
Career Karma
careerkarma.com โ€บ blog โ€บ python โ€บ replace item in list in python: a complete guide
Replace Item in List in Python: A Complete Guide: A Complete Guide
December 1, 2023 - You can replace items in a list using a Python for loop. To do so, we need to the Python enumerate() function. This function returns two lists: the index numbers in a list and the values in a list.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-replace-values-in-a-list-in-python
How to Replace Values in a List in Python? - GeeksforGeeks
A lambda is an anonymous function in python that contains a single line expression. Here we gave one expression as a condition to replace value. ... We can use for loop to iterate over the list and replace values in the list.
Published ย  January 4, 2025
Find elsewhere
๐ŸŒ
Ceos3c
ceos3c.com โ€บ home โ€บ python โ€บ python list replace โ€“ simple & easy
Python List Replace - Simple & Easy
March 1, 2023 - That is a pretty simple and easy-to-understand way of replacing a list item in Python. Another way of achieving our goal would be to use enumeration with the enumerate() function: for index, color in enumerate(favorite_colors): if color == "Gray": favorite_colors[index] = "Beige" print(favorite_colors)Code language: Python (python) ... This way, we utilize a for loop in combination with the enumerate() function to locate the color "Gray" and replace it with the color "Beige".
๐ŸŒ
Python Pool
pythonpool.com โ€บ home โ€บ blog โ€บ 7 efficient ways to replace item in list in python
7 Efficient Ways to Replace Item in List in Python - Python Pool
May 7, 2023 - It consists of the expression which has to be printed into the new list, the loop statement, and the original list from which the new values will be obtained. We shall use list comprehension to append the string โ€˜ colorโ€™ to all the list elements of my_list. We shall replace the old values with the updated values. my_list = ['Red', 'Blue', 'Orange', 'Gray', 'White'] my_list = [(item+' color') for item in my_list ] print(my_list) ... Map() is a built-in function in python using which we can iterate over an iterable sequence without having to write a loop statement.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-replace-substring-in-list-of-strings
Replace substring in list of strings - Python - GeeksforGeeks
July 11, 2025 - The for loop iterates over each string in a. s.replace(s1, s2) replaces "world" with "universe" in each string. The modified string is stored in result using append(). re.sub() function allows replacing substrings based on patterns.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ curious about logic behind replacing elements of a list.
r/learnpython on Reddit: Curious about logic behind replacing elements of a list.
February 20, 2025 -

Let's say we have a list x = ["a","b","c","b"] in which I want to replace an element, or all elements of a specific value, let's say "b". The way to do it would be (putting aside some fancy methods and such):

x = ["a","b","c","b"]
for n in x:
    if n == "b":
        i = x.index(n)
        x[i] = "W"

which is fine. But I was wondering why do we need specify index of the n variable since python -in this case- already knows it. Why can't we do something like that:

x = ["a","b","c","b"]

for n in x:
    if n == "b":
        n = "W"
print(x)

The list will not be changed. Why not? Python knows which n we want to change, that's what the if statement is here for. So why do we need extra step of specifying the position of an object with its index? Is it something inherited from C language?

๐ŸŒ
PyTutorial
pytutorial.com โ€บ python-list-replace-simple-guide
PyTutorial | Python List Replace: Simple Guide
May 24, 2026 - We use simple steps, clear examples, and short explanations. By the end, you will know how to replace elements in any Python list. Python lists are mutable. This means you can change their content after creation. Unlike strings, you can modify a list directly. There is no built-in list.replace() method. But you can achieve the same result using indexing, slicing, and loops.
Top answer
1 of 3
1

There is a lot of duplication in your code. I would suggest:

import random

word = list('GTGATCCAGT')
BASES = "ACGT"

for index, base in enumerate(word[:5]):
    word[index] = random.choice(BASES.replace(base, ""))

word = "".join(word)

A trial run gives me:

>>> word
'TACTACCAGT'

Note the switch to a list - strings in Python are immutable, so you can't (easily) change an individual character. By contrast, lists are mutable, so you can switch the item at a given index without any fuss.

2 of 3
0

Your loop doesn't currently have enough information to do what you want: in particular, it doesn't know which base you are currently looking at, only what its value is. You could use the builtin enumerate to introduce that information, but a simpler way would be to change the logic so it doesn't rebuild the string each time - instead, write a generator that gives you each successive new_base, and join them all into new_word at the end. It looks like this:

def rebase(word):
    for base in word:
        print base
        if base == 'A':
           new_base = random.choice('CTG')
           print new_base
           yield new_base
        # etc
        else:
          # If you didn't change this base, yield the original one
          yield base

 new_word = word[:5] + ''.join(rebase(word[5:]))

You might also want to use a dictionary to avoid the chain of ifs - like this:

def rebase(word):
    possible_replacements = {'A': 'CTG', 'C': 'ATG'} # etc
    for base in word:
        print base
        try:
           yield random.choice(possible_replacements[base])
        except KeyError:            
          # If you didn't change this base, yield the original one
          yield base

new_word = word[:5] + ''.join(rebase(word[5:]))
๐ŸŒ
DEV Community
dev.to โ€บ zeyu2001 โ€บ replace-loops-map-and-filter-with-list-comprehensions-in-python-3lk1
Replace Loops, map() and filter() With List Comprehensions in Python - DEV Community
May 8, 2020 - I could do ยท numbers = [] for ... is i. This is equivalent to the for loop we used earlier: we add i to the list where i is a number from 1 to 11....
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 73883784 โ€บ how-to-replace-all-elements-of-a-list-using-a-for-loop
python - How to replace all elements of a list using a for loop - Stack Overflow
September 28, 2022 - The question here asks to make two lists/arrays in python and fill it with 0s initially and then occupy them with the relevant values. import numpy as np x = [] y = [] for i in range (0,101): x.append(0) y.append(0) xx = np.linspace(1,10,101) print(xx) for a in range (len(y)): for j in xx: fx = np.log(j) y[a] = fx for b in range (len(x)): for k in xx: x[b] = k print(x) print(" ") print(y) I used a nested for loop to traverse through the values in the xx list and used the log function and stored the values in a variable and then replace the 0s in the (y)list with the function values over each iteration.
๐ŸŒ
stataiml
stataiml.com โ€บ posts โ€บ 35_find_replace_string_python_list
Find and Replace Values in List in Python - stataiml
May 3, 2024 - You can find and replace string values in a list using a list comprehension or map() function in Python. new_list = [s.replace('old_string', 'new_string') for s in input_list] new_list = map(lambda s: str.replace(s, 'old_string', 'new_string'), input_list) The following examples demonstrate how to use list comprehension and map() functions to replace string values in a list in Python.