Let's explore the "any" and "all" built-in functions in Python.
A ๐งต
First of all, I'll teach you how to fish in Python before giving you the fish. ๐๐ฃ
The built-in "help" function will give you documentation in Python. Make liberal use of it and reach out to it before ceding control to a search engine.
These are "aggregation" or "reducing" functions. They take a sequence and collapse it to a single value.
"any" returns if any value was truthy.
"all" returns if all values were truthy.
Most examples look like this:
Generally, I don't have lists of true, false values. Rather I tend to create them using "predicate functions" and comprehensions. A predicate returns a true/false value:
You can also replace "and" and "or" with "all" and "any". Here is code that checks if a letter is alphanumeric, period, or underscore:
Here is another pattern. If I wanted to determine if all characters in a filename were "valid", I would probably use a for loop and check each character. However, such for loops can be replaced with "all":
Likewise, we can replace searching for loops with "any". Here I search if there is a negative number and show the equivalent "any" version:
I hope you enjoyed learning about patterns for "any" and "all".
Feel free to share to your network and follow me for more Python insights. ๐
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.