Python trick collection

Feb 14, 2021 00:00 · 159 words · 1 minute read Python

Some Python programming tricks that make my work easier.

1. The difference between * and ** and their usage in Python**

Sometimes * and ** are used when we write a function. Other times, * and ** are used when we call a function. What’s the difference?

When we create a function:

  • * collects all the positional arguments in a tuple, like my_function(*args).
  • ** collects all the keyword arguments in a dictionary, like my_function(**kwargs).
def my_function(*args, **kwargs):
        print(args)
        print(kwargs)

my_function(1, 2, 3, 4, 5, 6, a=2, b=3, c=5)

# output
(1, 2, 3, 4, 5, 6)
{'a': 2, 'c': 5, 'b': 3}

When we call a function:

  • * unpacks a list or tuple into position arguments.
  • ** unpacks a dictionary into keyword arguments.
args=[1, 2, 3, 4]
kwargs={'a': 10, 'b':20}
my_function(*args, **kwargs)  
# It is the same as my_function(1, 2, 3, 4, a=10, b=20)

# output
(1, 2, 3, 4)
{'a': 10, 'b': 20}

(To be continued…)

Reference:

tweet Share

Related Articles