Sequence unpacking
Extracting values and assigning them to variables. As list and tuple are ordered, they support unpacking. Unordered sequences like dictionaries don't support unpacking.
Example
python
# list
language = ['Python', 'PHP', 'NodeJS']
# unpacking
django, laravel, express = language
print(django, laravel, express)
# Python PHP Java
# tuple
color = (225, 110, 20)
red, green, blue = color
print(red, green, blue)
# 225 110 20use * to unpack rest of the values
python
language = ['Python', 'PHP', 'NodeJS']
# unpacking with *
django, *others = language
print(django, others)
# Python ['PHP', 'NodeJS']use _ to ignore values
python
language = ['Python', 'PHP', 'NodeJS']
# ignore values with _
django, _, express = language
print(django, express)
# Python NodeJSuse * to unpack list into positional arguments
When calling a function, you can unpack a list into positional arguments. List must have same length as number of positional arguments.
python
django = ['Python', 'MVT']
def create_django_app(language, architecture):
return f'App created with {language} using {architecture} architecture'
# unpacking with * into positional arguments
print(create_django_app(*django))
# App created with Python using MVT architectureuse ** to unpack dictionary into keyword arguments
When calling a function, you can unpack a dictionary into keyword arguments. Dictionary keys name and element length must match function arguments.
python
django = {
'language': 'Python',
'architecture': 'MVT',
}
def create_django_app(language, architecture):
return f'App created with {language} using {architecture} architecture'
# unpacking with ** into keyword arguments
print(create_django_app(**django))
# App created with Python using MVT architectureuse ** to copy keys from existing dictionary
When creating a new copy of a dictionary, you can copy keys from existing dictionary. Then you can override the values of the copied keys or even create new keys.
python
my_guitar = {
'brand': 'Ibanez',
'year': 2020,
}
# copy keys from existing dictionary, override value and create new key
my_new_guitar = {**my_guitar, 'year': 2021, 'color': 'Aqua'}
print(my_new_guitar)
# {'brand': 'Ibanez', 'year': 2021, 'color': 'Aqua'}use ** to merge dictionaries
You can merge dictionaries using ** operator.
python
guitar_info ={
'design': 'RG',
'body': 'Poplar',
'neck': 'Maple',
'color': 'Aqua',
}
guitar_manufacturer = {
'brand': 'Ibanez',
'year': 2020,
}
# merge dictionaries
guitar = {**guitar_manufacturer, **guitar_info}
print(guitar)
# {'brand': 'Ibanez', 'year': 2020, 'design': 'RG', 'body': 'Poplar', 'neck': 'Maple', 'color': 'Aqua'}You could also use | operator to merge dictionaries. python > 3.9
python
guitar = guitar_manufacturer | guitar_info