Python 중고뉴비로서 배우는게 참 많다.
배열의 두 요소를 서로 맞바꾼다고하면 전통적으로(?) 이렇게 작성한다.
tmp = heap[curr]
heap[curr] = heap[child]
heap[child] = tmp하지만 Python에서는 다중 할당(multiple assignment)과 튜플 언패킹(tuple unpacking)을 이용해 단 한 줄로 스왑(swap)을 해결할 수 있다.
heap[curr], heap[child] = heap[child], heap[curr]
어떻게 동작할까?
- 등호 우측의 heap[child], heap[curr]는 튜플(heap[child], heap[curr])로 묶이게 된다.
- 등호 왼쪽의 heap[curr], heap[child]에는 튜플의 값이 순서대로 할당된다.
'프로그래밍 > Python' 카테고리의 다른 글
| Gevent 알아보기 (0) | 2025.09.11 | 
|---|---|
| [Python] Pipeline Pattern 구현 (0) | 2025.08.26 | 
| [해결방법] ImportError: libGL.so.1: cannot open shared object file: No such file or directory (0) | 2025.05.07 | 
| Pydantic Serialize시 오류 : Object of type <Enum> is not JSON serializable 해결방법 (0) | 2025.03.28 | 
| [FastAPI] 요청/응답 로깅하는 법 (0) | 2025.01.20 |