Python Forum
How does 'any' and 'all' work? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How does 'any' and 'all' work? (/thread-18821.html)



How does 'any' and 'all' work? - ibzi - Jun-02-2019

So i searched the internet for how these two functions work. This is what i gathered. they work like all works if all are true and any works if any are true. Now that i understand but i didn't get to know how i can apple them into my programs maybe if you have some easy examples on how these could actually be used then provide them! and if you have a better explanation on these then also tell me that i'll be more than glad.

Thanks! Smile


RE: How does 'any' and 'all' work? - michalmonday - Jun-02-2019

people = ['John', 'Feodor', 'Henry']
is_thirsty_states = [True, False, False]
is_hungry_states = [True, True, True]
is_drunk_states = [False, False, False]

if any(is_thirsty_states):
    print('Someone is thirsty (at least 1 person).')

if all(is_hungry_states):
    print('Everyone is hungry.')

if not any(is_drunk_states):
    print('No one is drunk, everyone is sober.')
Output:
Someone is thirsty (at least 1 person). Everyone is hungry. No one is drunk, everyone is sober.



RE: How does 'any' and 'all' work? - metulburr - Jun-02-2019

There is the built in help that gives the docstring explanation and instructions when its more complicated. You do not usually have to search the internet for simple explanations.

help(any)
any(iterable, /)
    Return True if bool(x) is True for any x in the iterable.
    
    If the iterable is empty, return False.
help(all)
all(iterable, /)
    Return True if bool(x) is True for all values x in the iterable.
    
    If the iterable is empty, return True.



RE: How does 'any' and 'all' work? - perfringo - Jun-02-2019

Some additional tidbits.

After learning built-in help as suggested by metulburr you can turn to Python documentation for more information: all(), any()

You can learn that both functions have short-circuiting feature meaning that they will stop when first False is encountered (function all) or when first True (any).

As somewhat practical example is determining whether string is valid DNA sequence.

>>> allowed = ['a', 'c', 'g', 't']
>>> dna = 'tatcagaaaacacgcgcttaagtgagcggaacgggtggaacaaggttgta'
>>> all(char in allowed for char in dna)
True                          
>>> dna = 'tatcagaaaacacgcgcttaagtgagcggaacgggtggaacaagguttgta'   # there is 'u'
>>> all(char in allowed for char in dna)
False	
Is there any number in sequence which is divisible both with 2 and 3:

>>> lst = [2, 3, 7, 11, 18, 20]
>>> any(num % 2 == 0 and num % 3 == 0 for num in lst)
True