any() and all() in Python with Examples (2024)

Introduction to any() and all()

In this tutorial, we'll be covering the any() and all() functions in Python.

The any(iterable) and all(iterable) are built-in functions in Python and have been around since Python 2.5 was released. Both functions are equivalent to writing a series of or and and operators respectively between each of the elements of the passed iterable. They are both convenience functions that shorten the code by replacing boilerplate loops.

Both methods short-circuit and return a value as soon as possible, so even with huge iterables, they're as efficient as they can be.

The and/or Operators

Let's remind ourselves how the and/or operators work, as these functions are based on them.

The or Operator

The or operator evaluates to True if any of the conditions (operands) are True.

print("(2 == 2) or (3 == 3) evaluates to: " + str((2 == 2) or (3 == 3)))print("(2 == 2) or (3 == 2) evaluates to: " + str((2 == 2) or (3 == 2)))print("(2 == 0) or (3 == 2) evaluates to: " + str((2 == 0) or (3 == 2)))

Output:

(2 == 2) or (3 == 3) evaluates to: True(2 == 2) or (3 == 2) evaluates to: True(2 == 0) or (3 == 2) evaluates to: False

We can chain multiple ors in a single statement, and it will again evaluate to True if any of the conditions are True:

print(str(False or False or False or True or False))

This results in:

True

The and Operator

The and operator evaluates to True only if all conditions are True:

print("(2 == 2) and (3 == 3) evaluates to: " + str((2 == 2) and (3 == 3)))print("(2 == 2) and (3 == 2) evaluates to: " + str((2 == 2) and (3 == 2)))print("(2 == 0) and (3 == 2) evaluates to: " + str((2 == 0) and (3 == 2)))

Output:

(2 == 2) and (3 == 3) evaluates to: True(2 == 2) and (3 == 2) evaluates to: False(2 == 0) and (3 == 2) evaluates to: False

Similarly to or, we can chain multiple and operators, and they will evaluate to True only if all the operands evaluate to True:

print(str(True and True and True and False and True))

This results in:

False

any()

The method any(iterable) behaves like a series of or operators between each element of the iterable we passed. It's used to replace loops similar to this one:

for element in some_iterable: if element: return Truereturn False

We get the same result by simply calling any(some_iterable):

print(any([2 == 2, 3 == 2]))print(any([True, False, False]))print(any([False, False]))

Running this piece of code would result in:

TrueTrueFalse

Note: Unexpected behavior may happen when using any() with dictionaries and data types other than boolean. If any() is used with a dictionary, it checks whether any of the keys evaluate to True, not the values:

dict = {True : False, False: False}print(any(dict))

This outputs:

True

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Whereas, if any() checked the values, the output would have been False.

The method any() is often used in combination with the map() method and list comprehensions:

old_list = [2, 1, 3, 8, 10, 11, 13]list_if_even = list(map(lambda x: x % 2 == 0, old_list))list_if_odd = [x % 2 != 0 for x in old_list]print(list_if_even)print(list_if_odd)print("Are any of the elements even? " + str(any(list_if_even)))print("Are any of the elements odd? " + str(any(list_if_odd)))

This outputs:

[True, False, False, True, True, False, False][False, True, True, False, False, True, True]Are any of the elements even? TrueAre any of the elements odd? True

Note: If an empty iterable is passed to any(), the method returns False.

If you'd like to read more about the map(), filter() and reduce() functions, we've got you covered!

all()

The all(iterable) method evaluates like a series of and operators between each of the elements in the iterable we passed. It is used to replace loops similar to this one:

for element in iterable: if not element: return Falsereturn True

The method returns True only if every element in iterable evaluates to True, and False otherwise:

print(all([2 == 2, 3 == 2]))print(all([2 > 1, 3 != 4]))print(all([True, False, False]))print(all([False, False]))

This outputs:

FalseTrueFalseFalse

Note: Just like with any(), unexpected behavior may happen when passing dictionaries and data types other than boolean. Again, if all() is used with a dictionary, it checks whether all of the keys evaluate to True, not the values.

Another similarity with any() is that all() is also commonly used in combination with the map() function and list comprehensions:

old_list = ["just", "Some", "text", "As", "An", "example"]list_begins_upper = list(map(lambda x: x[0].isupper(), old_list))list_shorter_than_8 = [len(x) < 8 for x in old_list]print(list_begins_upper)print(list_shorter_than_8)print("Do all the strings begin with an uppercase letter? " + str(all(list_begins_upper)))print("Are all the strings shorter than 8? " + str(all(list_shorter_than_8)))

This outputs:

[False, True, False, True, True, False][True, True, True, True, True, True]Do all the strings begin with an uppercase letter? FalseAre all strings shorter than 8? True

Note: If an empty iterable is passed to all(), the method returns True! This is because the code for all() checks if there are any False elements in the iterable, and in the case of an empty list there are no elements and therefore there are no False elements either.

Boolean Conversion and any(), all() Functions

A common cause of confusion and errors when using any logical operators, and therefore when using any() and all() as well, is what happens when the elements aren't of the boolean data type. In other words, when they aren't exactly True of False but instead have to be evaluated to True or False.

Some programming languages don't evaluate non-boolean data types to booleans. For example Java would complain if you tried something along the lines of if("some string") or if(15) and tell you that the type you used can't be converted to boolean.

Python on the other hand does no such thing, and will instead convert what you passed to boolean without warning you about it.

Python converts most things to True with a few exceptions:

  • Any numerical value equal to 0 (including 0.0) is treated as False. A common misconception here is that negative values (-2, -3.3,...) are treated as False as well, they are not treated as False!
  • Any empty sequence (or collection) is treated as False, including empty strings, empty lists, etc. Keep in mind that unexpected behavior might happen when using all() with an empty iterable (it will return True).
  • The actual boolean value False is of course treated as False as well as the special value None.

A few examples of how we can use the way Python "boolean-izes" other data types with any() and all().

list_of_strings = ["yet", "another", "example",""]print("Do all strings have some content?", all(list_of_strings))list_of_ints = [0, 0.0, -2, -5]print("Are any of the ints different from 0?", any(list_of_ints))

This outputs:

Do all strings have some content? FalseAre any of the ints different from 0? True

Keep in mind that you might still want to write more readable code by not using implicit boolean conversion like this.

Conclusion

Both the any() and all() functions are there for convenience sake and should be used only when they make the code shorter but maintain the readability.

In this article, we've jumped into the any() and all() functions and showcased their usage through several examples.

any() and all() in Python with Examples (2024)

References

Top Articles
The 15 Best Places with Hookah in Dubai
What Is a Hookah Lounge and What To Expect | Hookah.com
Readyset Ochsner.org
Truist Park Section 135
Red Wing Care Guide | Fat Buddha Store
Directions To Lubbock
Sinai Web Scheduler
Canelo Vs Ryder Directv
Best Cav Commanders Rok
Bc Hyundai Tupelo Ms
Best Food Near Detroit Airport
Kris Carolla Obituary
2016 Ford Fusion Belt Diagram
Operation Cleanup Schedule Fresno Ca
Nutrislice Menus
Extra Virgin Coconut Oil Walmart
Find Such That The Following Matrix Is Singular.
Vistatech Quadcopter Drone With Camera Reviews
Weather Rotterdam - Detailed bulletin - Free 15-day Marine forecasts - METEO CONSULT MARINE
Honda cb750 cbx z1 Kawasaki kz900 h2 kz 900 Harley Davidson BMW Indian - wanted - by dealer - sale - craigslist
1773X To
Silive Obituary
ELT Concourse Delta: preparing for Module Two
Craigslist Clinton Ar
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Anotherdeadfairy
Kingdom Tattoo Ithaca Mi
Catchvideo Chrome Extension
Cor Triatriatum: Background, Pathophysiology, Epidemiology
Mjc Financial Aid Phone Number
Angel del Villar Net Worth | Wife
Dentist That Accept Horizon Nj Health
Ofw Pinoy Channel Su
Deleted app while troubleshooting recent outage, can I get my devices back?
Beaver Saddle Ark
Personalised Handmade 50th, 60th, 70th, 80th Birthday Card, Sister, Mum, Friend | eBay
Honda Ruckus Fuse Box Diagram
How much does Painttool SAI costs?
Adam Bartley Net Worth
Henry Ford’s Greatest Achievements and Inventions - World History Edu
Scarlet Maiden F95Zone
Sas Majors
Skyward Marshfield
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Panolian Batesville Ms Obituaries 2022
How to Install JDownloader 2 on Your Synology NAS
How the Color Pink Influences Mood and Emotions: A Psychological Perspective
The Sports Academy - 101 Glenwest Drive, Glen Carbon, Illinois 62034 - Guide
Stitch And Angel Tattoo Black And White
Meet Robert Oppenheimer, the destroyer of worlds
Actress Zazie Crossword Clue
Race Deepwoken
Latest Posts
Article information

Author: Arline Emard IV

Last Updated:

Views: 6169

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.