C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python any() FunctionThe python any() function returns True if any item in an iterable is true, otherwise it returns False. Note : If the iterable is empty, then it returns False.Signatureany(iterable) ParametersIterable: It takes an iterable object such as list, dictionary etc. ReturnIt returns true if at least one element of an iterable is true. Python any() Function Example 1Let's see how any() works for lists? l = [4, 3, 2, 0] print(any(l)) l = [0, False] print(any(l)) l = [0, False, 5] print(any(l)) l = [] print(any(l)) Output: True False True False Explanation: In the above example, we take some list (l) that contains some items, and then check the output of the code. In first case, a list containing all true values so it returns TRUE. In second case, both items contains a false value. So, it returns FALSE. In third case, two items contain false and one item contains true. So, it returns TRUE. In the last case, there is an empty list. So, it returns FALSE. Python any() Function Example 2The below example shows how any() works with strings. s = "This is awesome" print(any(s)) # 0 is False # '0' is True s = '000' print(any(s)) s = '' print(any(s)) Output: True True False Explanation: In the above example, a string returns True value. In second case, '000' behaves like a string so, it returns True value. In third case, a string is empty. So, it returns False value. Python any() Function Example 3The below example shows how any() works with dictionaries. d = {0: 'False'} print(any(d)) d = {0: 'False', 1: 'True'} print(any(d)) d = {0: 'False', False: 0} print(any(d)) d = {} print(any(d)) # 0 is False # '0' is True d = {'0': 'False'} print(any(d)) Output: False True False False True Explanation: In the above example, we take some dictionaries that contain some items. In the first case, 0 returns False value. In the second case, one item is a false value and other value is true value. So, it returns true value. In the third case, both the values are false values, so it returns false value. In the fourth case, a dictionary is empty. So, it returns a False value. In the fifth case, '0' behaves like a string. So, it returns a True value.
Next TopicPython Functions
|