Skip to content
Advertisement

How to replace a word to another word in a list python?

If I have this list:

['hello', 'world', 'goodbye', 'world', 'food']

Is it possible to replace every world to any other word without using any auto command, I am thinking about something like this:

if 'world' in list:
    'world' in list == 'peace'

Advertisement

Answer

You can use a list comprehension with an if-else.

list_A = ['hello', 'world', 'goodbye', 'world']
list_B = [word if word != 'world' else 'friend' for word in list_A]

You now have a new list, list_B, where all instances of the word “world” have been replaced with “friend”.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement