Joachim Schork
Joachim Schork

Reputation: 2147

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?

Upvotes: 1

Views: 1789

Answers (5)

ThePyGuy
ThePyGuy

Reputation: 18476

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))

Upvotes: 4

blackraven
blackraven

Reputation: 5637

You could use map() function with syntax map(<function>, <iterable>). However you will have to code it into a list() to yield the results, for example:

my_list = ["yes", "yes", "no", "yes", "no", "yes"]
my_list_logical = list(map(lambda x: x == "yes", my_list))
print(my_list_logical)

Output

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

Upvotes: 2

Chis
Chis

Reputation: 9

Yes and this is the most logical way I can think of

my_list = ["yes", "yes", "no", "yes", "no", "yes"]
my_list_logical = []
for i in my_list:
   if i == “yes”:
      my_list_logical.append(True)
   else:
      my_list_logical.append(False)

Upvotes: 1

Jan
Jan

Reputation: 43199

You may very much use a list comprehension:

my_list = ["yes", "yes", "no", "yes", "no", "yes"]
result = [item == "yes" for item in my_list]

Which yields

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

Upvotes: 1

David Kaftan
David Kaftan

Reputation: 2174

Probably the best answer is to use the package numpy. Numpy arrays act similarly to R vectors.

import numpy as np
my_list = np.array(["yes", "yes", "no", "yes", "no", "yes"])
my_list == "yes"
array([ True,  True, False,  True, False,  True])

Upvotes: 3

Related Questions