*) in PythonThe asterisk (*) in Python has several powerful uses, depending on the context. Here's a summary based on the content in your image:
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
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
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')
zip() and Unpackinga = ['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')]
** 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.