본문 바로가기

프로그래머/Python

[윤성우의 열혈 파이썬 중급편] 11. 튜플의 패킹과 언패킹

출처 : 윤성우의 열혈 파이썬 : 중급

11. 튜플의 패킹과 언패킹

  • 튜플 패킹 : 하나 이상의 값을 튜플로 묶는 행위
  • 튜플 언패킹 : 튜플에 묶여 있는 값들을 풀어내는 행위
tri_one = (12, 15)
print(tri_one)

tri_three = (12, 25)
bt, ht = tri_three
print(bt, ht)

nums = (1, 2, 3, 4, 5)
n1, n2, *others = nums      # 둘 이상의 값을 리스트로 묶을 때 *를 사용
print(n1)       # 1
print(n2)       # 2
print(othres)   # [3, 4, 5]

first, *others, last = nums

*others, n1, n2 = nums

# 리스트를 대상으로도 동일하게 동작한다
nums = [1, 2, 3, 4, 5]
n1, n2, *others = nums

함수 호출 및 반환 과정에서의 패킹과 언패킹

def ret_nums():
    return 1, 2, 3, 4, 5

nums = ret_nums()
print(nums)     # (1, 2, 3, 4, 5)

n, *others = ret_nums()
print(n)        # 1
print(other)    # [2, 3, 4, 5]

def show_nums(n1, n2, *other):
    print(n1, n2, other, sep = ', ')

print(show_nums(1, 2, 3, 4))        # 1, 2, (3, 4)
print(show_nums(1, 2, 3, 4, 5))     # 1, 2, (3, 4, 5)
  • 매개변수 앞에 * 가 오면 이는 나머지 값들은 튜플로 묶어 이 변수에 저장하겠다는 의미이다

  • 튜플의 패킹에서 소괄호는 생략이 가능하다

def sum(*nums):
    s = 0
    for i in nums:
        s += i
    return s

sum(1, 2, 3)

def show_man(name, age, height):
    print(name, age, height, sep = ', ')

print(p)        # ('Yoon', 22, 180)
show_man(*p)    # Yoon, 22, 180

p = ['Park', 21, 177]
show_man(*p)    # Park, 21, 177
  • 함수 호출 시 *가 사용되면 이는 튜플 언패킹으로 이어진다
  • 이렇듯 *은 위치에 따라서 패킹을 의미하기도 하고 언패킹을 의미하기도 한다
  • 언패킹은 리스트를 대상으로도 작동한다
t = (1, 2, (3, 4))
a, b, (c, d) = t
print(a, b, c, d, sep = ', ')   # 1, 2, 3, 4

p = 'Hong', (32, 178), '010-1234-5678', 'Korea'
na, (ag, he), ph, ad = p
print(na, he)   # Hong 178

na, (_, he), _, _ = p
print(na, he)   # Hong 178

for 루프에서의 언패킹

ps = [('Lee', 172), ('Jung', 182), ('Yoon', 179)]
for n, h in ps:
    print(n, h, sep = ', ')

# Lee, 172
# Jung, 182
# Yoon, 179

ps = (['Lee', 172], ['Jung', 182], ['Yoon', 179])
for n, h in ps:
    print(n, h, sep = ', ')