반응형
    
    
    
  python에서 햇갈리기 쉬운 equality와 identity에 대해 정리합니다.

Summary
1. True / False를 비교할 때는 if문에 변수만 사용한다.
- boolean에 대한 값은 True인지 False인지 명확하기 때문에 그냥 사용
2. Equality를 검증할 때는 == 또는 != 연산자를 사용
- 값이 맞는지만 비교
3. Identiy를 검증할 때는 is 또는 is not을 사용
- 객체 자체가 완전히 일치하는지를 비교
None의 비교
None은 python에서 정의된 NoneType 클래스임
None은 값이 아니라 Identity를 비교하기 때문에 ==이 아니라 is를 사용
※ Equality를 비교해도 상관은 없지만 Identity를 비교해야 성능상의 이점이 있음
다음은 smaple code 입니다.
None 값을 Equality 와 Identity 방식으로 비교를 하였을 때 어느 정도의 성능 차이가 나는데 보여줍니다.
※ code는 "파이썬답게 코딩하기" 책의 source code를 사용하였습니다.
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
 | 
 #!/usr/bin/python3 
import timeit 
def average(items): 
    sum = 0 
    for item in items: 
        sum += float(item) 
    return sum / len(items) 
def check_performance(compare_expression, condition): 
    results = timeit.Timer(compare_expression, setup=condition).repeat(100, 10000) 
    return average(results) 
def main(): 
    print("compare x is not None") 
    print("equality : %s" % check_performance("x == None", "x = 1")) 
    print("identity : %s" % check_performance("x is None", "x = 1")) 
    print("compare x is None") 
    print("equality : %s" % check_performance("x == None", "x = None")) 
    print("identity : %s" % check_performance("x is None", "x = None")) 
if __name__ == "__main__": 
    main() 
 | 
cs | 
실행 결과를 보면, x 값이 None이거나, 아니거나 상관없이 identity 방식으로 비교하는 것이 더 빠름을 보여줍니다.

반응형
    
    
    
  '프로그래밍 > PYTHON' 카테고리의 다른 글
| python - Mixin (0) | 2021.03.13 | 
|---|---|
| python - Pandas Dataframe Handling(Creation, Filtering, Translation) (0) | 2021.02.22 | 
| python - Comprehension, Generator expression (0) | 2021.02.11 | 
| python - Yield, Generator (0) | 2021.02.10 | 
| [환경설정] python - Linux anaconda (0) | 2021.02.10 |