Python/이론, 기초

[Python] 파이썬 any(), all()

파송송 2023. 3. 9. 22:24
728x90

파이썬의 내장 함수로 iterable 한 객체를 받아 조건에 맞으면 True 맞지 않으면 False를 출력한다.


any()

하나라도 True가 있다면 True를 반환(OR과 유사함)

any([False, True, False])
any([False, False, False])
any([True, True, True])

 


all()

모두 True일 때, True를 반환(And와 유사함)

all([False, True, False])
all([False, False, False])
all([True, True, True])

for

for 문과 함께 사용하여 반복문 전체를 하나의 list로 볼 수 있다.

cur = 5
temp = [1,3,2,2,4]

if any(cur<num for num in temp):
	print("There exist number that is larger than 5")
else:
	print("There not exist number that is larger than 5")


cur = 5
temp = [1,3,2,2,7]

if any(cur<num for num in temp):
	print("There exist number that is larger than 5")
else:
	print("There not exist number that is larger than 5")


cur = 5
temp = [1,3,2,2,7]

if all(cur<num for num in temp):
	print("all number is larger than 5")
else:
	print("all number is not larger than 5")

cur = 5
temp = [8,10,9,8,7]

if all(cur<num for num in temp):
	print("all number is larger than 5")
else:
	print("all number is not larger than 5")


주의

for문의 모든 결과값을 list 형태로 보기 때문에 따로 쓰는 게 불가능함

for num in temp:
	if any(5<num):
		print('larger than 5')

TypeError: 'bool' object is not iterable

728x90