If I have this list:
JavaScript
x
2
1
['hello', 'world', 'goodbye', 'world', 'food']
2
Is it possible to replace every world
to any other word without using any auto command, I am thinking about something like this:
JavaScript
1
3
1
if 'world' in list:
2
'world' in list == 'peace'
3
Advertisement
Answer
You can use a list comprehension with an if-else.
JavaScript
1
3
1
list_A = ['hello', 'world', 'goodbye', 'world']
2
list_B = [word if word != 'world' else 'friend' for word in list_A]
3
You now have a new list, list_B
, where all instances of the word “world” have been replaced with “friend”.