Matt Harrison Profile picture
Python ๐Ÿ + Data Science ๐Ÿš€ trainer @__metasnake__ ๐Ÿฆœ Speaker โœ Author ๐Ÿ‘จโ€๐Ÿซ Instructor (@Stanford) ๐Ÿ“ฃ DM for Sponsorship

Oct 28, 2021, 8 tweets

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.

Keep scrolling