언패킹(unpacking)은 테이너(예: 리스트, 튜플, 딕셔너리)의 요소들을 개별 변수나 인자로 분리하는 과정임.

 

코드를 더 간결하고 유연하게 만들며, 특히 함수 인자를 다룰 때 유용함.

 

주로 *(별표)와 **(이중 별표) 연산자를 사용한다.

 

 

* 연산자는 리스트나 튜플을 언패킹할 때 사용함.

  • 이는 함수 호출 시 위치 인자(positional arguments)로 언패킹할 때 사용한다.
numbers = [1, 2, 3]
a, b, c = *numbers  # a=1, b=2, c=3

def add(x, y, z):
    return x + y + z

print(add(*numbers))  # 6

 

 

** 연산자는 딕셔너리를 언패킹 할 때 사용한다.

  • 함수 호출 시 키워드 인자(keyword arguments)로 언패킹할 때 사용한다.
person = {"name": "Alice", "age": 30}
def greet(name, age):
    print(f"Hello, {name}. You are {age} years old.")

greet(**person)  # Hello, Alice. You are 30 years old.

 

 

함수 정의에서의 언패킹:

  • 함수가 임의의 개수의 인자를 받을 수 있게 한다.
def print_info(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(1, 2, 3, name="Alice", age=30)

 

 

리스트 병합 및 딕셔너리 병합:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = [*list1, *list2]  # [1, 2, 3, 4, 5, 6]

dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = {**dict1, **dict2}  # {"a": 1, "b": 2, "c": 3, "d": 4}

 

 

나머지 값 수집: 

first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [2, 3, 4, 5]

 

 

생성자에서 언패킹:

city_filter = Filter(**{
    "must": [{
        "key": "city",
        "match": {
            "value": city_of_interest
        }
    }]
})

# 이 코드는 아래 코드와 동일 

city_filter = Filter(must=[{
    "key": "city",
    "match": {
        "value": city_of_interest
    }
}])

+ Recent posts