89DEVs

Python any() function

The Python any() function can be used to determine if any element of an iterable is True. If any element is True it returns True, otherwise False.

any() on Python lists

Example 1: list1 = [False, True, False] print(any(list1)) In this example True is returned, because at least one of the booleans in the list is True. True Example 2: list2 = [0, 1, 2, 3] print(any(list2)) In this example True is returned, because 1, 2, 3 are True, while 0 is False. True Example 3: list3 = [] print(any(list3)) In this example False is returned, because the list is empty. False Example 4: list4 = [0, False, ''] print(any(list4)) In this example False is returned, because all items in the list are False.

any() on Python strings

Example 1: string1 = 'example string' print(any(string1)) In this example True is returned, because the string is True. True Example 2: string2 = '0' print(any(string2)) In this example False is returned, because the string '0' is True. The string '0' is different than the integer 0, which is False. True Example 3: string3 = '' print(any(string3)) In this example False is returned, because the empty string is False. False

any() on Python dictionaries

If the any() function is used on a Python dictionary, it will return True if at least one key is True. If all keys are False or the dictionary is empty, False is returned. It is important to understand, that the keys matter not the values of the dictionary. Example 1: dictionary1 = {0: 'hello'} print(any(dictionary1)) In this example False is returned, because the key 0 is False. False Example 2: dictionary2 = {} print(any(dictionary2)) In this example False is returned, because the dictionary is empty. False Example 3: dictionary3 = {0: 'hello', False: 'world'} print(any(dictionary3)) In this example False is returned, because both keys 0 and False are False. False Example 4: dictionary4 = {'0': 'hello'} print(any(dictionary4)) In this example True is returned, because the key '0' is a string and True. True

any() syntax

The syntax of the any function is: any(iterable)

any() arguments

The any() function takes exactly one iterable (list, string, dictionary) as argument. In case more or less than one iterable are given, an TypeError occurs.

any() return value

The any() function returns a boolean value: True, if at least one element is True False, if all of the elements are False False, if the iterable is empty
condition return value
All values are True True
One value is True, others are False True
One value is False, others are True True
All values are False False
The iterable is empty False
In case all values have to be True, the all() function should be used.

                
        

Summary


Click to jump to section