practivceAlgorithm/PYTHON 기능연습

[Python] Python List, Dictionary, Set등 참조형 자료구조 복사

findTheValue 2022. 7. 24. 21:51

Python의 List와 Set, Dictionary등은 call by reference한다. 

즉 

a = [1, 2, 3]
b = a
b.append(4)
print(a)

# [1, 2, 3, 4]

할당 된 주소가 공유된다.

때문에

자료형 a 와 동일한 자료형 b를 만들기 위해 다음과 같은 방법을 사용할 수 있다.

from copy import copy, deepcopy

l = [1, 2, 3]
s = {1, 2, 3}
d = {1:1, 2:2, 3:3}

# use copy(얕은복사)
l_copy = copy(l)
s_copy = copy(s)
d_copy = copy(d)

# use deepcopy(깊은 복사)
l_deepcopy = deepcopy(l)
s_deepcopy = deepcopy(s)
d_deepcopy = deepcopy(d)

# slicing(새로운 주소 할당)
l_slicing = l[:]

# comprehension(새로 만들기)
l_comprehension = [i for i in l]
s_comprehension = {i for i in s}
d_comprehension = [i:j for i, j in d.items()]

보통 이중으로 리스트나 dictionary에 call by reference하는 자료형이 중첩되었을 경우 깊은 복사가 필요한데

이때 deepcopy는 무겁고 느리기 때문에 comprehension을 사용하면 좋습니다.