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 replace 'chicken' with something else, what method i can use that is like .replace() but for a list?
Asked
Active
Viewed 1e+01k times
18

Patrick Tran
- 191
- 1
- 1
- 3
2 Answers
28
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'))

amad-person
- 431
- 1
- 4
- 12

Ry-
- 218,210
- 55
- 464
- 476
-
What if I want to change only partial part of the word and my list has more than 2 parts in the value? – PM0087 Apr 18 '21 at 14:22
4
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']

ShadowRanger
- 143,180
- 12
- 188
- 271