1

So basically I have a huge list of strings, for example

list = ["hello", "my", "name", "is"] 

etc...

and I want to ask the user a question, if the user responses with a word that is in my list I want to replace it with "yes". How would I do this, everything that I have tried has failed. Thanks!

2 Answers 2

1

List comprehension:

# user input in user_input
new_list = [item if item != user_input else "yes" for item in old_list] 

This replaces anything that's equal to the user_input with "yes".

Tip: don't shadow the built-in list.

Output:

>>> old_list = ["hello", "my", "name", "is"] 
>>> user_input = "hello"
>>> new_list = [item if item != user_input else "yes" for item in old_list] 
>>> new_list
['yes', 'my', 'name', 'is']
Sign up to request clarification or add additional context in comments.

Comments

0

Imagine this is your list

 INPUT_MATCH = 'yes'
 L = ["hello", "my", "name", "is"] 

You are asking user to input

user_input = raw_input("Enter your input")

if user_input in set(L): #reason to convert list to set for less expensive search
    L[L.index(user_input)] = INPUT_MATCH

Comments

Your Answer

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