๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ Python

[Python] *, ** ์‚ฌ์šฉ๋ฒ•

by dev.py 2025. 2. 18.

ํŒจํ‚น, ์–ธํŒจํ‚น

func(*iterable)

iterable ๊ฐ์ฒด๋ฅผ ์–ธํŒจํ‚นํ•˜์—ฌ, ๊ฐœ๋ณ„ ์ธ์ž๋กœ ์ „๋‹ฌํ•จ

>>> def who(a,b,c):
	print(a,b,c, sep =',')
    

>> who(*[1,2,3])
1, 2, 3
>> who(*[0.1, 0.2, 0.3])
0.1, 0.2, 0.3

 

func(**dict)

>>> def who(a,b,c):
	print(a,b,c, sep =',')
    
>> d = dict(a = 1, b = 2, c = 3)
>> who(*d) # key๊ฐ€ ์ „๋‹ฌ๋œ๋‹ค.
a, b, c
>> who(**d) # value๊ฐ€ ์ „๋‹ฌ๋œ๋‹ค.
1, 2, 3

 

def func(*args)

๊ฐ’๋“ค์ด ํŠœํ”Œ๋กœ ๋ฌถ์—ฌ์„œ args์— ์ „๋‹ฌ๋œ๋‹ค.

>>> def func(*args):
		print(args)
        
 >> func()
 ()
 >> func(1)
 (1,) # ๋‹จ์ผ ์š”์†Œ์ผ๋•Œ๋Š” ,๊ฐ€ ๋ถ™์–ด์•ผ ํŠœํ”Œ๋กœ ์ธ์‹๋จ (์•„๋‹ˆ๋ฉด ์ •์ˆ˜)
 >> func(1, 2)
 (1, 2)
 >> func(1, 2, 3)
 (1, 2, 3)

 

def func(**args)

์ „๋‹ฌ๋˜๋Š” ๋‚ด์šฉ์ด dict(๋”•์…”๋„ˆ๋ฆฌ)๋กœ ๋ฌถ์—ฌ์„œ args์— ์ „๋‹ฌ๋œ๋‹ค.

>>> def func(**args):
		print(args)

>>>func(a=1)
{'a': 1}
>>>func(a=1, b=2)
{'a': 1, 'b':2}
>>>func(a=1, b=2, c=3)
{'a': 1, 'b': 2, 'c': 3}

 

 

def func(*args1, **args2)

ํ•  ์ˆ˜๋Š” ์žˆ์ง€๋งŒ, ํ˜ผ๋ž€์Šค๋Ÿฝ๊ธฐ ๋•Œ๋ฌธ์— ์“ฐ์ง„ ๋ง์ž

>>> def func(*args1, **args2):
		print(args1) # ํŠœํ”Œ
        print(args2) # ๋”•์…”๋„ˆ๋ฆฌ
        
        
>>> func()
()
{}
>>> func(1, a = 1)
(1,)
{'a' : 1}
>>> func(1, 2, a = 1, b = 2)
(1, 2)
{'a': 1, 'b': 2}