Python any() Function

The 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.

Signature

Parameters

Iterable: It takes an iterable object such as list, dictionary etc.

Return

It returns true if at least one element of an iterable is true.

Python any() Function Example 1

Let's see how any() works for lists?

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 2

The below example shows how any() works with strings.

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 3

The below example shows how any() works with dictionaries.

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.






Latest Courses