-
[WEEK01/DAY02] python : 배열의 복사본을 삭제했는데 원본이 삭제될 때SW Jungle/TIL (Today I Learned) 2022. 9. 25. 02:48
python으로 재귀호출 알고리즘 문제를 풀던 중,
원본 배열이 필요해서 남겨두기 위해 복사본을 만들고
복사본의 일부를 del 명령어를 이용해 삭제했는데
원본이 같이 삭제되어 버리는 현상이 발생했다.
예를 들면,
a = [1, 2, 3, 4, 5, 6] b = a # [1, 2, 3, 4, 5, 6] del b[0] # b배열의 0번째를 삭제했으므로 b배열은 [2, 3, 4, 5, 6]이 된다. # 나는 b배열의 일부분을 삭제했으니, a배열은 남아있어야 하는데... print(a) # [2, 3, 4, 5, 6] print(b) # [2, 3, 4, 5, 6] # ??????
이렇게 되는 것이다.
왜 그런가 하니, 이것은 python의 객체 개념을 이해하지 못한 나의 잘못이었다.
python에는 mutable 객체와 immutable 객체가 있다.
변수에 다른 변수를 할당 ( a = b 처럼 ) 했을 때,
immutable 객체는 해당 값을 복사해오지만 mutable 객체는 그 주소값을 복사해온다.
아래는 python 객체별 구분 표이다.
class 설명 구분 list mutable 한 순서가 있는 객체 집합 mutable set mutable 한 순서가 없는 고유한 객체 집합 mutable dict key와 value가 맵핑된 객체, 순서 없음 mutable bool 참,거짓 immutable int 정수 immutable float 실수 immutable tuple immutable 한 순서가 있는 객체 집합 immutable str 문자열 immutable frozenset immutable한 set immutable list는 mutable 객체이기 때문에 주소값만 복사되었던 것이고, 따라서 복사본을 지워도 원본이 같이 지워졌던 것이다.
이렇게 주소값만 복사되는 것을 '얕은 복사(shallow copy)'라고 한다.
그러면 내가 원하는 것은 깊은 복사(deep copy)인데, 어떻게 구현해야 할까?
바로 python에서 제공하는 copy.deepcopy 메소드를 이용하면 된다.
import copy a = [1, 2, 3, 4, 5, 6] b = copy.deepcopy(a) # [1, 2, 3, 4, 5, 6] del b[0] # [2, 3, 4, 5, 6] print(a) # [1, 2, 3, 4, 5, 6] print(b) # [2, 3, 4, 5, 6] # b배열만 삭제된 것을 확인할 수 있다.
참고자료 : https://wikidocs.net/16038
풀고 있던 문제 : 백준 5568번 "카드 놓기"
https://www.acmicpc.net/problem/5568
Special thanks to. 김재현'SW Jungle > TIL (Today I Learned)' 카테고리의 다른 글
[WEEK01/DAY05] 백준 문제 : 연산자 끼워넣기 (0) 2022.09.28 [WEEK01/DAY04] 백준 문제 : 수 정렬하기 3 (0) 2022.09.27 [WEEK01/DAY01] 백준 문제 : 소수 찾기 (0) 2022.09.24 [WEEK00/DAY03] Jinja2 값을 Javascript에서 사용하기 (0) 2022.09.22 [WEEK00/DAY02] flask jsonify - ObjectId 전달 에러 (2) 2022.09.21