any() method in Python


The any() method returns true if any element of iterable is true, or false if iterable is empty. It is equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

If all are null, 0, or False, it returns False; if (as long as there are non-null or 0 or False) not all are null, 0, or False, it returns True.

Note

The return value for empty tuples (parentheses) and empty lists (middle brackets), empty dictionary dictionary empty collection set (curly brackets) is False.

Related course: Complete Python Programming Course & Exercises

Syntax

any(iterable)

Description of parameters.

  • iterable - iterative, including string, list, dict, tuple, set()

Return value.

How any() method in Python works

The following example shows how to use the any() function

# List list, none of the elements are empty or 0. True
print(any([1,2,3,4,5]))

# list, there is an empty element. true
print(any(['a','b','c','d',''']))

# list list, there is an element of 0. True
print(any([1,2,3,0,5]))

# list, all elements are 0,'',false. false
print(any([0,False,''])

# elementtuple, none of the elements are empty or 0. True
print(any((1,2,3,4,5)))

# elementtuple, there is an empty element. true
print(any(('a','b','c','d','')))

# elementtuple, there is an element of 0. True
print(any((1,2,3,0,5)))

# elementtuple, all elements are 0,'',false.False
print(any((0,False,''))

#Null list. false
print(any([]))

#empty tuple.
print(any(()))

#empty set empty dictionary.
print(any({}))

output

True
True
True
False
True
True
True
False
False
False
False

any method in python

Derivation: Use python to determine if a string contains elements from a list. (The elements of the list are also strings, of course.)

place = ['Buenos Aires','Monte Video','Brasilia']
str = "I want to go Monte Video"

if any(element in str for element in place): #member operator and derivative
    print("string contains Monte Video"

output

string contains Monte Video

This is where the any() function is learned.

any() in Python interactive shell

You can use any() from the shell. This works on some data types, but not on all as the example below demonstrates.

>>> any([0])
False
>>> any([0,1,2])
True
>>> any([0,1,2,''])
True
>>> any([0,''])
False
>>> any((0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> any((0,))
False
>>> any((0,12))
True
>>> any((0,12,''))
True
>>> any((0,''))
False
>>> any({})
False
>>> any({'a':1})
True
>>> any({''})
False
>>> any({0})
False
>>>