[operator] asterisk (*)

반디·2023년 3월 6일
0

Python

목록 보기
5/11
post-thumbnail

곱하기나 power 이외의 asterisk operator의 쓰임새를 알아봅니다.

unpacking

  • set, list, tuple, dictionary와 같은 iterable object 안의 element들을 풀어헤침
  • dictionary를 unpack 할 때는 **를 이용 \rightarrow callable object나 dictionary 안에서만 사용가능!
    (dictionary 안의 element를 하나의 변수로 unpack 할 수는 없음)
Example
  1. unpacking using *
animals = ['dog', 'cat', 'monkey', 'rabbit']
print("using *:", *animals)

first, *middle, last = [i for i in range(5)]
print("middle:", middle)

  1. unpacking string using *
*target, = 'hello' #tuple로 처리해야 함 
print("target:", target)

*tmp1, tmp2  = 'hello'
print(f"tmp1: {tmp1} tmp2: {tmp2}")

  1. unpacking dictionaries using **
animals = {'dog':1, 'cat':2, 'rabbit':4}
food = {'cookie':1, 'cake':2, 'roll':4}
merged_dict = {**animals, **food}
print(merged_dict)

packing in functions: args and kwargs

  • 개수가 정해지지 않은 변수를 함수의 parameter로 사용할 수 있도록 함 ex)*args
  • dictionary를 위해서는 **를 이용
Example
  1. *args
def sum_using_asterisk(*args):
    result = 0
    for i in args:
        result += i
    return result
    
numbers = [1, 2, 3]
print(f"sum_using_asterisk: {sum_using_asterisk(*numbers)}")

  1. **kwargs
def make_person(name, **kwargs):
    result = name + ': '
    for key, value in kwargs.items():
        result += f'{key} = {value} '
    return result
        
print(make_person('Melissa', id=12112, location='london'))

참고문헌

profile
꾸준히!

0개의 댓글