백엔드 2일차: 파이썬 값 비교 시 is 를 쓰면 안 되는 이유

임로빈·2023년 12월 8일
post-thumbnail

chapter 8

!Mission!

값 비교에는 is를 쓰면 안 되는 이유를 찾아서 작성해 보자!

다른 사람이 쓴 글을 읽고 내가 이해한 내용을 그대로 작성해 보자.

왜 1 == 1.0 을 입력했을 때에는
True가 출력되고,

1 is 1.0 을 입력했을 때에는
False가 출력될까?

is는 ==와 같은 역할을 하면서 다른 역할을 한다.
1과 1.0은 같은 값이지만, 타입이 다르다.

1은 정수이고, 1.0은 소수점을 가진 실수이다.
둘의 값은 같지만, 객체가 완전히 동일하지 않다.

객체는 생성하면서 메모리에 저장되는데
이때 고유한 ID가 생기면서 메모리 주소값을 가진다.

is는 이때 고유 ID 번호를 비교해서
동일한 객체인지 확인한다.

  • id함수로 둘의 ID를 뽑아보면,
    1의 ID는 "140667464597744",
    1.0의 ID는 "140667172295920"로 추출된다.

따라서 값이 일치하는지 확인하려면,
is 가 아닌 ==를 써야 한다.

참고.

위키독스 4. 파이썬 연산 3) 비교 연산
https://wikidocs.net/22216

profile
https://readyoun.tistory.com/

2개의 댓글

comment-user-thumbnail
2025년 1월 22일

A Game for Competitors
If you’re competitive, you’ll love [url=https://slope-online.org/]slope[/url] The endless nature of the game makes it all about beating your own high score or challenging friends. It’s a game that’s easy to share and enjoy with others.

답글 달기
comment-user-thumbnail
2025년 1월 22일

Repetitive but Fun
While the slope gameplay doesn’t change much, the core mechanics are so fun that it doesn’t matter. The repetitive nature of Slope is part of its charm, and it’s a testament to how engaging the gameplay is.

답글 달기