본문 바로가기
파이썬 이야기

Part 20. 멤버 연산자와 식별 연산자

by 핸들이없는8톤트럭 2022. 8. 4.
반응형

멤버 연산자

좌측의 값이 우측의 자료에 속해 있는지 확인하는 연산자입니다. 이렇게 문장으로 보시면 이해하기 힘드실 것입니다. 아래 코드를 확인해보시죠.

 

in : 우측의 자료에 좌측 자료가 속하는지 여부를 확인

ex) 3 in [ 1, 3, 4, 6]

 

not in : 우측 자료에 좌측 자료가 속하지 않는지 여부 확인

ex) 3 in [1, 3, 5, 6]

 

# 멤버 연산자 (Membership Operation)

x = [101, 202, 303, 404, 505]
print(101 in x)
print(104 in x)

x = ('apple', 'mango', 'banana')
print('apple' in x)
print('pear' in x)

x= set()
print('apple'in x)
print('pear' in x)

x = {'apple' : 0, 'mango' : 10, 'banana' : 2, 'pear' :5}
print('apple' in x) #딕셔너리는 key를 기준으로 한다.
print(10 in x) # 딕셔너리의 value는 in에서 기준이 되지 못한다
print(10 in x.values()) # 딕셔너리의 value를 받아준 다음에 사용 가능

supported = ['png', 'jpg']
filename = 'cat.png'
if filename.split('.')[-1] in supported :
    print (filename + ' is supported')
else :
    print(filename + ' is not supported')

 

 

결과값

True
False
True
False
False
False
True
False
True
cat.png is supported

Process finished with exit code 0

 

식별 연산자(Identity operators)

두 피연산자가 동일한 객체를 가르키는지 여부를 확인하는 연산자입니다. 두 피연산자의 값이 같더라도 다른 객체일 수 있습니다. id()를 이용해 객체의 고유한 id를 알 수 있습니다. --> is & is not

 

# 식별 연산자 (identity operator)
print()
x=4
y=6
print(x==y) # 값을 비교
print(x is y) # 값이 아닌, 객체를 비교

x = ['apple']
y = ['apple']
print( x== y)
print(x is y)
print(id(x))
print(id(y))

x.append('banana') # 기존 리스트에 내용을 추가 , 기존 객체 유지
# x= x + {'banana'} 새로운 리스트를 만들어서 새로운 객체로 변경
# x += {'banana'} #  파이썬이 스스로 최적화해서 기존 객체를 유지
print(x == y)
print(x is y)
print(f'id(x):{id(x)}')
print(f'id(y):{id(x)}')

print()
x = ['apple']
y = x
print(x == y)
print(x is y)
print(f'id(x):{id(x)}')
print(f'id(y):{id(x)}')

 

결과값

False
False
True
False
4473953728
4474091584
False
False
id(x):4473953728
id(y):4473953728

True
True
id(x):4474116032
id(y):4474116032

Process finished with exit code 0

반응형

'파이썬 이야기' 카테고리의 다른 글

Part 22. 파이썬의 흐름 제어란  (0) 2022.08.04
Part 21. 연산자의 우선순위  (0) 2022.08.04
Part 19. 파이썬 연산자의 모든 것  (0) 2022.07.28
Part 18. 문자열  (0) 2022.07.28
Part 18. 집합 자료형  (0) 2022.07.25

댓글