python公式ドキュメントはこちら
Pythonで用意されている組み込み関数の中の any関数の使い方です。引数に指定したイテラブルオブジェクトの要素の要素のいずれかがTrueと判定されるとTrueを返します。すべてFalseであればFalseを返します。
目次
any関数の書式
any(iterable)基本的な使い方
any関数は引数に指定したイテラブルオブジェクトの要素のいずれかがTrueと判定されるとTrueを返します。すべてFalseであればFalseを返します。
print(any([True, False, False]))
# True
print(any([False, False, False]))
# Falseリストに限らず、タプルや集合set型も引数に指定可能です。
print(any((True, False, False)))
# True
print(any({True, False, False}))
# Trueany関数は以下のコードと等価です。
def any(iterable):
for element in iterable:
if element:
return True
return Falseしたがって、空のイテラブルオブジェクトの場合にはfor文に入らず、常にFalseを返します。
def any(iterable):
# ❶イテラブルが空の場合は、以下のfor文に入らない
for element in iterable:
if element:
return True
# ❷Falseを返す
return False
print(any([]))
# False
コメント