[Python]#8 unpacking operator *

Clay Ryu's sound lab·2023년 8월 12일
0

Framework

목록 보기
24/48

The operator can be used in various scenarios for different purposes. Keep in mind that the operator is used for unpacking elements from iterables like lists, tuples, or sets, and the ** operator (double asterisks) is used for unpacking key-value pairs from dictionaries.

Here are some examples of using the unpacking operator:

  1. Function arguments – Pass elements of an iterable as separate positional arguments.
def print_coords(x, y, z):
    print(f"Coordinates: ({x}, {y}, {z})")

coords = (1, 2, 3)
print_coords(*coords)  # Equivalent to print_coords(1, 2, 3)
  1. Function call – Combine multiple iterables into a single one.
fruits = ['apple', 'banana', 'cherry']
vegetables = ['carrot', 'cucumber', 'lettuce']

groceries = [*fruits, *vegetables]
print(groceries)
# Output: ['apple', 'banana', 'cherry', 'carrot', 'cucumber', 'lettuce']
  1. Variable unpacking – Assign elements of an iterable to separate variables. This usage is very useful to make an object from a certain class which requires a number of parameters.
numbers = [1, 2, 3, 4, 5]

first, *middle, last = numbers

print(first)    # Output: 1
print(middle)   # Output: [2, 3, 4]
print(last)     # Output: 5
  1. Merging dictionaries – Merge the contents of two or more dictionaries into a new one using the unpacking operator ** (with two asterisks).
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

merged_dict = {**dict1, **dict2}
print(merged_dict)
# Output: {'a': 1, 'b': 3, 'c': 4} (Note: The value for key 'b' is updated by the value from dict2)
profile
chords & code // harmony with structure

0개의 댓글