0

I have a list of string

[a,b,c]

How do I check if all the variables are the string 'Ready'?.

I want to return True if all variables are Ready else False.

I really appreciate any help you can provide.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
NAS_2339
  • 353
  • 2
  • 13

1 Answers1

3

You can use all and a list comprehension:

lst = ['Ready', 'Ready', 'Ready']
print(all(i == 'Ready' for i in lst))

Output:

True

Thanks for @schwobaseggl's comment, you can also do this:

print(all(map("Ready".__eq__, lst)))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 1
    Note that you do not have to build list with booleans in order to use all, i.e. you might do: `print(all(i == 'Ready' for i in lst))`. – Daweo Dec 18 '20 at 10:12
  • Yup, you should really use `all` with a generator, not a list comprehension. – user2390182 Dec 18 '20 at 10:16
  • @schwobaseggl Check this out: https://stackoverflow.com/questions/9060653/list-comprehension-without-in-python/9061024#9061024 – U13-Forward Dec 18 '20 at 10:17
  • @Daweo Check this out: https://stackoverflow.com/questions/9060653/list-comprehension-without-in-python/9061024#9061024 – U13-Forward Dec 18 '20 at 10:17
  • Agree... but is a nice answer , just remove `[]` – adir abargil Dec 18 '20 at 10:18
  • @adirabargil Check this out: https://stackoverflow.com/questions/9060653/list-comprehension-without-in-python/9061024#9061024 – U13-Forward Dec 18 '20 at 10:19
  • @U11-Forward Yup but that is a special case for `str.join` where all elements will always be needed and the space for the final string needs to be allocated. `all`'s big advantage is the short-circuit (it can stop on the first non-"Ready") which you negate by building a list of booleans for all elements. – user2390182 Dec 18 '20 at 10:20
  • 1
    @schwobaseggl True maybe i change it now: – U13-Forward Dec 18 '20 at 10:20
  • That is not true for the `all` function at all... try timeit this: `all( not i==0 for i in range (10000))` vs `all([ not i==0 for i in range (10000)])` – adir abargil Dec 18 '20 at 10:21
  • Talking performance, one could argue that `all(map("Ready".__eq__, lst))` is even better as it won't have to repeatedly lookup the `__eq__` method on a different `str` object. – user2390182 Dec 18 '20 at 10:28