asterisk(*) 에 관하여

Leejaegun·2025년 3월 30일

코딩테스트 시리즈

목록 보기
36/49

✅ Explanation of Asterisk (*) in Python

The asterisk (*) in Python has several powerful uses, depending on the context. Here's a summary based on the content in your image:

1. Unpacking Iterables

You can use * to unpack values from a list, tuple, or any iterable into individual variables.

a, *b = [1, 2, 3, 4]
print(a)  # 1
print(b)  # [2, 3, 4]

Or the reverse:

*a, b = [1, 2, 3, 4]
print(a)  # [1, 2, 3]
print(b)  # 4

2. Argument Unpacking in Function Calls

You can use * to unpack a list or tuple into function arguments:

def f(a, b, c):
    print(a, b, c)

params = ['a', 'b', 'c']
f(*params)  # same as f('a', 'b', 'c')

Output:

a b c

3. Collecting Arguments in Functions

You can use *args in function definitions to collect extra positional arguments as a tuple:

def f(*args):
    print(args)

f('a', 'b', 'c')  # Output: ('a', 'b', 'c')

4. Using with zip() and Unpacking

a = ['a1', 'a2']
b = ['b1', 'b2']
c = ['c1', 'c2']
d = ['d1', 'd2']

print(list(zip(a, b, c, d)))
# [('a1', 'b1', 'c1', 'd1'), ('a2', 'b2', 'c2', 'd2')]

zipped = list(zip(a, b, c, d))
unzipped = list(zip(*zipped))
print(unzipped)
# [('a1', 'a2'), ('b1', 'b2'), ('c1', 'c2'), ('d1', 'd2')]

5. Keyword Argument Unpacking with ``**

** works similarly to *, but for dictionaries:

date_info = {'year': '2020', 'month': '01', 'day': '7'}
new_info = {**date_info, 'day': '14'}
print(new_info)
# {'year': '2020', 'month': '01', 'day': '14'}

This is used to unpack dictionary key-value pairs.

profile
Lee_AA

0개의 댓글