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?
There are three ways to replace an item in a Python list. You can use list indexing or a for loop to replace an item. If you want to create a new list based on an existing list and make a change, you can use a list comprehension. You may decide that you want to change a value in a list.
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
Replace Multiple Values in a Python List. There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With