[Python]대입 표현식(:=)

변도진·2024년 6월 16일
0

Python

목록 보기
9/14
post-thumbnail

대입 표현식

표현식의 일부 값을 변수에 대입하는 문법이다.
바다코끼리 연산자라고도 불리며 Python 3.8에 추가되었다.

:=을 통해 사용한다.

예시

대입 연산자 사용 전

코드

string = "hello world"
if string.index("world") > 3:
    print(string.index("world"))

결과

6

대입 연산자 사용 후

코드

string = "hello world"
if (world_index := string.index("world")) > 3:
    print(world_index)

결과

6

가독성이 훨신 좋다.

코드

def f():
    print("호출됨")
    return 5

if f() > 2:
    print(f())

결과

호출됨
호출됨
5

대입 연산자 사용 후

코드

def f():
    print("호출됨")
    return 5

if (x:=f()) > 2:
    print(x)

결과

호출됨
5

함수 호출을 줄일 수 있는 면에서 성능도 뛰어나다.

주의

대입 연산자의 우선순위는 다른 연산자보다 낮다.
그러니 사용에 주의해야 한다.

예시

코드

if (x := 5) > 2:
    print(x)
if x := 5 > 2: # 5 > 2 우선 연산
    print(x)

결과

5
True

참조

https://docs.python.org/ko/3/whatsnew/3.8.html
(CPython Grammar 보다 찾음)

profile
낚시하고 싶다.

0개의 댓글