공감하기
본문 바로가기
  • [!] Manual from the past has just arrived
개발일지/Python

[Python] Call-by-value vs Call-by-reference

by Puilin 2023. 11. 16.

c언어에서는 포인터를 통해 변수에 직접 접근하여 값을 변경할 수 있다.

void swap(int *x1, int *x2) {
    int temp = *x1;
    *x1 = *x2;
    *x2 = temp;
}

int main(void) {
    int arr[2] = {0, 3};
    swap(&arr[0], &arr[1]);
    return 0;
}

 

python은 명시적으로 call-by-reference와 call-by-value를 구분하지 않는다.

대신에, mutable한 객체와 immutable한 객체에 따라 동작이 달라진다.

int, string과 같은 immutable한 객체는 call-by-value를, list와 같은 mutable한 객체는 call-by-reference 처럼 동작하게 된다.

 

따라서 위 swap 함수를 python에 가져와서 그대로 옮긴 다음 call-by-reference처럼 동작하게 하려면, mutable한 객체를 이용해서 값을 넘겨주어야 한다.

def swap(xs, x1, x2):
    temp = xs[x1]
    xs[x1] = xs[x2]
    xs[x2] = temp

arr = [0, 3]
swap(arr, 0, 1)

 

그런데 굳이 이렇게 코드를 짜는 경우는 거의 없는 것 같다.

python은 한줄로 이 모든 동작을 완성할 수 있다.

arr[0], arr[1] = arr[1], arr[0]

 

python이 강조하는 단순함의 철학이 돋보이는 코드 중 하나인 것 같다.


참고 : 1) https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/

'개발일지 > Python' 카테고리의 다른 글

[PyMongo] 기본 transaction 정리  (0) 2023.01.06