An iterable is an object that returns an iterator. An iterator is used to iterate through an object. Examples of iterables in python are list, tuple, string, dictionary etc._ any()_ in python is used to check if any element in an iterable is True. That means it will return True if anything inside an iterable is True, else it will return False. The syntax of any() is as below :
The iterable parameter in the above function is an iterable object, such as list, tuple, set, dictionary or a string. In this tutorial, we will learn how any() behaves with these iterables.
As we have explained earlier, any() will return the following outputs : True: If any value is true. True: If all values are true. True: If any value is false, but not all. False: If all the values are false. False: If the iterable is empty.
As you can see in the example above, any() is useful for checking if an item in a list is ‘False’ or if the list is empty. Instead of iterating through the list to check if all items are ’True’ or not, we can use ‘any()’. Let’s analyze each print statements one by one.
The commented numbers in the above program denote the step number below :
- Only one value is 0, but others are non-zero. So it results True.
- All are non-zero numbers. So, True.
- True because all are non-zero numbers and one value is True.
- One value is False but others are non-zero numbers. So, the result is True.
- False because it is an empty list.
- False because members are either zero or False.
Tuples are used to hold a sequence of objects in Python. Python tuples are similar to Python lists. They are used to hold a sequence of objects. But, tuples are immutable, unlike lists. We can’t change them. The items are comma separated and placed inside a parenthesis. We can use any() with a tuple similarly like a list.
A string is also iterable and we can use any() on a string object as well. As you can see that only for the empty string, it results False. For non-empty strings, the result is always True. This is another way to check if a string is empty or not.
You can use any() in any iterable to check quickly if all values are False or not. Try to run the programs on your side and let me know if you have any queries.