Python Forum
How does 'any' and 'all' work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How does 'any' and 'all' work?
#1
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
Reply
#2
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.
Reply
#3
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.
Recommended Tutorials:
Reply
#4
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020