There’s nothing built-in, but it’s just a loop to do the replacement in-place:
for i, word in enumerate(words):
if word == 'chicken':
words[i] = 'broccoli'
or a shorter option if there’s always exactly one instance:
words[words.index('chicken')] = 'broccoli'
or a list comprehension to create a new list:
new_words = ['broccoli' if word == 'chicken' else word for word in words]
any of which can be wrapped up in a function:
def replaced(sequence, old, new):
return (new if x == old else x for x in sequence)
new_words = list(replaced(words, 'chicken', 'broccoli'))
There’s nothing built-in, but it’s just a loop to do the replacement in-place:
for i, word in enumerate(words):
if word == 'chicken':
words[i] = 'broccoli'
or a shorter option if there’s always exactly one instance:
words[words.index('chicken')] = 'broccoli'
or a list comprehension to create a new list:
new_words = ['broccoli' if word == 'chicken' else word for word in words]
any of which can be wrapped up in a function:
def replaced(sequence, old, new):
return (new if x == old else x for x in sequence)
new_words = list(replaced(words, 'chicken', 'broccoli'))
No such method exists, but a list comprehension can be adapted to the purpose easily, no new methods on list needed:
words = 'I like chicken'.split()
replaced = ['turkey' if wd == "chicken" else wd for wd in words]
print(replaced)
Which outputs: ['I', 'like', 'turkey']
Videos
Try using a list comprehension and a conditional expression.
>>> a=[1,2,3,1,3,2,1,1]
>>> [4 if x==1 else x for x in a]
[4, 2, 3, 4, 3, 2, 4, 4]
You can use the built-in enumerate to get both index and value while iterating the list. Then, use the value to test for a condition and the index to replace that value in the original list:
>>> a = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
>>> for i, n in enumerate(a):
... if n == 1:
... a[i] = 10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]