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.

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You can try using list comprehension:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.