0

I have a list contains different names:

list = ['Tom', 'Mary', 'Robin', 'Tom']

What I want to do, is to replace 'Tom' with 'MESSAGE' and everyone else as 'RESPONSE'.

Like below: list = ['MESSAGE', 'RESPONSE', 'RESPONSE', 'MESSAGE']

Is there a way to do it? Preferably using only one line of code.

Linus Ng
  • 7
  • 1

3 Answers3

4

It's a simple list comprehension:

["MESSAGE" if name == "Tom" else "RESPONSE" for name in list]

As a side note, do not use built-ins such as list to name your variables.

Selcuk
  • 52,758
  • 11
  • 94
  • 99
1

Its a try, and its in a single Line. If the list contains only 2 unique values, then

replacedList = ['MESSAGE' if item == 'Tom' else 'RESPONSE' for item in list]

reference from here

Praveen
  • 139
  • 1
  • 7
0

You can try using list comprehension:

list = ["MESSAGE" if item == "Tom" else "RESPONSE" for item in list]
huytc
  • 907
  • 5
  • 19