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.
Example of using any() :
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.
any() with a list :
Let’s try to use any() with a list :
The commented numbers in the above program denote the step number below :
1. Only one value is 0, but others are non-zero. So it results True.
2. All are non-zero numbers. So, True.
3. True because all are non-zero numbers and one value is True.
4. One value is False but others are non-zero numbers. So, the result is True.
5. False because it is an empty list.
6. False because members are either zero or False.
any() with a tuple :
The output is same as the above example.
any() with string :
As you can see that only for the empty string, it results False. For non-empty strings, the result is always True.
any() with dictionaries :
Dictionaries are a list of key-value pairs. any() will check only the keys,i.e. if any one of the key is true, it will result True. Else, False
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.
You might also like :
- Python List
- Find average of numbers in a list
- List all the files in a Zip file using Python 3
- Write a simple calculator program in Python 3
- Python program to sort values of one list using second list
- Python tutorial to remove duplicate lines from a text file