Python Tuples: Unpacking Tuples

Unpacking Tuples

When creating a tuple, we often assign values to it, a process known as “packing” a tuple:

books = ("1984", "Brave New World", "Fahrenheit 451")

In Python, it’s also possible to extract these values back into separate variables, a process known as “unpacking”:

Basic Unpacking

Here’s how you can unpack a tuple into individual variables:

books = ("1984", "Brave New World", "Fahrenheit 451") (dystopian, futuristic, classic) = books print(dystopian) # Output: 1984 print(futuristic) # Output: Brave New World print(classic) # Output: Fahrenheit 451 

Note: The number of variables must exactly match the number of values in the tuple. If they do not match, use an asterisk (*) to collect the excess values into a list.

Using the Asterisk (*) for Flexible Unpacking

If you have more values than variables, you can use an asterisk (*) to capture the remaining values into a list:

books = ("1984", "Brave New World", "Fahrenheit 451", "The Handmaid's Tale", "The Road") (dystopian, futuristic, *others) = books print(dystopian) # Output: 1984 print(futuristic) # Output: Brave New World print(others) # Output: ['Fahrenheit 451', 'The Handmaid's Tale', 'The Road'] 

If the asterisk is placed in a position other than the last variable, Python will collect values into that variable until the remaining variables have the same number of values:

books = ("1984", "Brave New World", "Fahrenheit 451", "The Handmaid's Tale", "The Road") (dystopian, *others, classic) = books print(dystopian) # Output: 1984 print(others) # Output: ['Brave New World', 'Fahrenheit 451', 'The Handmaid's Tale'] print(classic) # Output: The Road 

Leave a Comment

Buy samsung galaxy watch 6. The technical storage or access that is used exclusively for anonymous statistical purposes. 99, it offers high quality sound and integration with other smart home devices.