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”.