About 2093 letters

About 10 minutes

#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)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#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)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#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)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

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)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#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)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#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)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Created in 5/15/2025

Updated in 5/21/2025