Skip to content

Instantly share code, notes, and snippets.

@stephenfrench9
Created October 3, 2022 19:15
Show Gist options
  • Save stephenfrench9/e52a8f0796818fb4f9ff729ac1a43ef1 to your computer and use it in GitHub Desktop.
Save stephenfrench9/e52a8f0796818fb4f9ff729ac1a43ef1 to your computer and use it in GitHub Desktop.
Basic usage for * and ** operators
# the * and ** operator in assignment, reference, and function signatures
# * Reference: unroll the list. Something has to catch it:
a = ['aaa', 'aa']
[*a]
{*a}
def two_i(a, b):
print(a)
print(b)
two_i[*a]
# * Assignment: (I am not sure of the utility)
[*cc] = ['a', 'aaaaae']
# same as
cc = ['a', 'aaaaae']
# ** Reference:
ie1 = {'a': 1, 'b': 2}
ie2 = {'b': c, 'd': 2}
{*ie1, *ie2} # a set with the keys
{**ie1, **ie2} # the merged dictionary
# function signatures
# *x in a function signature means x will be a list of all the args
def print_n(*x):
for ele in x:
print(ele)
print_n('the', 'first', 'option', 'is', 'always', 'the', 'best')
# *x in a function signature means x will be a dictionary of all the kwargs
def print_kwargs(**x):
for k, v in x.items():
print(k, v)
print_n(one='the', two='first', three='option')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment