#Python's unpacking operation
Unpacking allows us to extract elements from an iterable object (such as a list, tuple, dictionary, etc.) into multiple variables.
#Sequence Unpacking
The most common form of unpacking is extracting elements from tuples or lists. For example:
student_info:tuple[str, int, str] = ("Yukari", 17, "female")
name, age, sex = student_info
print(name, age, sex)
#Partial Unpacking
You can use underscores (_) in sequence unpacking to ignore elements you don't need. For example:
students:list[str] = ["Tom", "Jerry", "Spike", "Tuffy"]
first, _, _, last = students
print(first, last)
#Using the Asterisk
Using an asterisk (*) allows you to unpack tuples, lists, or sets into individual elements. For example:
students:list[str] = ["Tom", "Jerry", "Spike", "Tuffy", "Tyke", "Butch"]
warp1 = [students]
warp2 = [*students]
print(warp1)
print(warp2)
You can also use an asterisk (*) in sequence unpacking to collect multiple elements into a list. For example:
students:list[str] = ["Tom", "Jerry", "Spike", "Tuffy", "Tyke", "Butch"]
first, *_, last = students # _ is a list holding the intermediate elements
print(first, last)
#Key-Value Unpacking
Using the items method, you can get key-value pairs from a dictionary, which can be unpacked individually:
score_list:dict[str,int] = {
'Tom': 88,
'Jerry': 99,
'Spike': 66
}
# Unpack a single key-value pair
name, score = list(score_list.items())[0]
print(name, score)
# Simplify the for loop with key-value unpacking
for key, value in score_list.items():
print(key, value)
#Dictionary Unpacking with Double Asterisks
Using double asterisks (**) allows you to unpack a dictionary into individual key-value pairs. For example:
score_list:dict[str,int] = {
'Tom': 88,
'Jerry': 99,
'Spike': 66
}
warp = {**score_list}
print(warp)