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?
#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


Messages In This Thread
How does 'any' and 'all' work? - by ibzi - Jun-02-2019, 10:50 AM
RE: How does 'any' and 'all' work? - by metulburr - Jun-02-2019, 12:27 PM
RE: How does 'any' and 'all' work? - by perfringo - Jun-02-2019, 03:46 PM

Forum Jump:

User Panel Messages

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