소개

  • 반복 가능한 객체의 요소들 중 하나라도 참(True)인 경우 참(True)을 반환하는 내장함수
  • 파라미터로 반복 가능한 객체(Iterable) 을 받는다.
  • 반복 가능한 객체가 비어있거나, 모든 요소가 거짓(False)인 경우 False 를 반환한다.
1
2
# 시그니처
any(iterable) -> bool
1
2
3
4
5
6
# 정의
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

사용법

1
any(Iterable)

예시

반복 가능한 객체에 숫자 2026이 포함되어있는지 여부 확인

  • 포함된 경우
1
2
3
4
year_list = [x for x in range(2050)]
any([x==2026 for x in year_list])

# >> True
  • 포함되지 않은 경우
1
2
3
4
year_list = [x for x in range(2025)]
any([x==2026 for x in year_list])

# >> False
  • 반복 가능한 객체가 비어있는 경우
1
2
3
4
year_list = []
any([x==2026 for x in year_list])

# >> False

generator와 any

  • generator 또한 Iterable이므로 any 함수를 사용할 수 있다.
1
2
3
4
5
6
if any(x == 2026 for x in (x for x in range(2050))):
    print("2026 in the generator")
else:
    print("there is no 2026")
    
# >> 2026 in the generator

any()의 연산 횟수

  • 정의에서 알 수 있듯, any 함수는 “처음 True를 만나는 경우” 혹은 “모든 요소를 순환한 뒤” 종료된다.
  • 즉, 반복 가능한 객체 안에 True 요소가 있다면 그 요소까지만 반복되며, True 요소가 없는 경우는 전체 리스트를 반복한다.
  • 아래는 테스트 코드
1
2
3
4
5
6
7
8
9
10
11
12
# 숫자를 반환하는 generator
count = 0 
def gen(num=2050):
    global count
    for i in range(1, num):
        count += 1 # 전역변수 count : 요소를 생산할 때마다 1씩 증가
        yield i

if any(x == 2026 for x in gen(2050)):
    print("2026 in the list")

print(f"count : {count}")
1
2
2026 in the list
count : 2026

Reference

Python Built-in Functions - any

Comments