Search code examples
pythonlistlogical-operators

Simple Way to Check Each List Element for Match with Particular String in Python


I have the following list in Python:

my_list = ["yes", "yes", "no", "yes", "no", "yes"]

I want to return a list of logical values, being True in case the corresponding list element in my_list is equal to "yes" and False in case the corresponding list element in my_list is equal to "no".

Desired output:

my_list_logical = [True, True, False, True, False, True]

I'm usually programming in R, and in R this could be done easily with the following code:

my_list == "yes"

I found a Python solution in this thread. However, the solution of this thread is very complicated, and I cannot believe that this is so much more complicated in Python than in R.

Is there a simple way on how to return a list of logicals based on my input vector?


Solution

  • You can use list comprehension:

    my_list = ["yes", "yes", "no", "yes", "no", "yes"]
    
    logical = [item=='yes' for item in my_list]
    

    OUTPUT:

    [True, True, False, True, False, True]
    

    Or, you can even use map:

    logical = list(map(lambda x: x=='yes', my_list))