문제
다음 Python 코드의 실행 결과를 쓰시오.
Pythondef build_chain(value, chain={}): chain[len(chain)] = value return chain print(build_chain('first')) print(build_chain('second')) print(build_chain('third', {10: 'new'})) print(build_chain('fourth'))
정답
{0: 'first'} {0: 'first', 1: 'second'} {10: 'new', 1: 'third'} {0: 'first', 1: 'second', 2: 'fourth'}
{0: 'first'}{0: 'first', 1: 'second'}{10: 'new', 1: 'third'}{0: 'first', 1: 'second', 2: 'fourth'}
해설
가변 기본 인자인 딕셔너리 {}는 함수 정의 시 한 번만 생성되어 모든 호출에서 공유된다. 첫 번째 호출에서 {0: 'first'}가 되고, 두 번째 호출에서는 기존 딕셔너리에 {1: 'second'}가 추가된다. 세 번째 호출은 새로운 딕셔너리 {10: 'new'}를 전달받아 독립적으로 작동하며 {10: 'new', 1: 'third'}가 된다. 네 번째 호출은 다시 공유된 기본 딕셔너리를 사용하여 {0: 'first', 1: 'second', 2: 'fourth'}가 된다.