English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonction en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Méthode d'utilisation de any() en Python et exemples

Built-in functions of Python

Si tout élément de l'itérable est True, la méthode any() renverra True. Sinon, any() renverra False.

The syntax of any() is:

any(iterable)

any() parameters

 The any() method in Python uses an iterable (list, string, dictionary, etc.).

From the returned value of any()

any() returns:

  • True if at least one element of the iterable is true

  • False if all elements are false or the iterable is empty

ConditionReturn value
All values are TrueTrue
All values are falseFalse

A value is true (other values are false)

True

A value is false (other values are true)

True
Empty iteratorFalse

Example1How to use any() with Python lists?

l = [1, 3, 4, 0]
print(any(l))
l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))

When running the program, the output is:

True
False
True
False

The any() method is used in a similar waytuplesand similar to listsSets.

Example2How to use any() with Python strings?

s = "This is good"
print(any(s))
# 0 is False
# '0' is True
s = '000'
print(any(s))
s = ''
print(any(s))

When running the program, the output is:

True
True
False

Example3How to use any() with Python dictionaries?

For dictionaries, if all keys (non-values) are false, any() returns False. If at least one key is true, any() returns True.

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))

When running the program, the output is:

False
True
False
False
True

Built-in functions of Python