Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method like .replace() for list in python? [duplicate]

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?

like image 746
Patrick Tran Avatar asked Mar 30 '17 02:03

Patrick Tran


People also ask

Is there a Replace function in Python for lists?

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.

How do you replace all occurrences in a list in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

How do you replace multiple values in a list Python?

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.


1 Answers

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'))
like image 105
2 revs, 2 users 98% Avatar answered Oct 07 '22 20:10

2 revs, 2 users 98%