0

How to get or/and of Booleans in python. For example I have a list of Booleans

lst = [True, True, False, False, True]

I want to define another Boolean variable based on condition in this lst. What is the best way of returning True if any one item is True within lst. Also how can I return True with the condition that all items are True within lst

Muhammad Rasel
  • 704
  • 4
  • 9
  • 6
    Take a look at the [`any()`](https://docs.python.org/3/library/functions.html#any) and the [`all()`](https://docs.python.org/3/library/functions.html#all) functions. These are built in and always available. – Alex Aug 06 '21 at 11:00

3 Answers3

4

Thanks. I solved using the following:

x = all(lst)
y = any(lst)
print(x,y)
Muhammad Rasel
  • 704
  • 4
  • 9
1

The any() and the all() function is the way to go:

lst = [True, True, False, False, True]

x=all(lst)
y=any(lst)

print(x,y)
alparslan mimaroğlu
  • 1,450
  • 1
  • 10
  • 20
  • 5
    I don't see the need to compare with `True`here. I think `x = any(i for i in lst)` or just `x = any(lst)` (the same for `all`) is just neater and more readable. – glglgl Aug 06 '21 at 11:05
  • Generator expressions are commonly used with `all` and `any` because you usually don't already have a sequence of Boolean values and have to create one. `lst`, however, *is* a sequence of Boolean values. – chepner Aug 06 '21 at 13:08
0

If all elements of your list are booleans, the faster and simplest way is

lst = [True, True, False, True]
condition = False not in lst

# in other words
(False not in lst) == all(lst)
(True in lst) == any(lst)

condition will be False if even one False in list

rzlvmp
  • 7,512
  • 5
  • 16
  • 45