Unpack Tuples

How to Unpack Tuples in Python – Tuple Unpacking Explained


How to Unpack Tuples in Python – Tuple Unpacking Explained | Devyra

Python – Unpacking Tuples

Author: Devyra Programming Team

Category: Python Programming Tutorials

Understanding Tuple Packing and Unpacking

In Python, a tuple is an immutable sequence of elements. When we group multiple values together into a tuple and assign them to a single variable, this is known as packing.

fruits = ("apple", "banana", "cherry")

Conversely, we can extract these values from the tuple and assign them to individual variables. This process is known as unpacking.

fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)

Note: The number of variables must match the number of items in the tuple. Otherwise, Python will raise a ValueError.

Using the Asterisk (*) in Tuple Unpacking

If you need to unpack only a few values while collecting the rest into a list, Python allows the use of an asterisk (*) before a variable name.

Example – Collect Remaining Items as a List:

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)

The variable red becomes a list containing the remaining items after the first two values.

Advanced Example – Asterisk in the Middle:

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)

Here, tropic receives all middle values, leaving the first and last elements assigned to green and red respectively.

For more Python tutorials and professional programming insights, visit Devyra, your trusted guide in coding education.

More From Author

Update Tuples

How to Update Tuples in Python: Add, Modify, and Remove Tuple Items

Loop Tuple

How to Loop Through a Tuple in Python – For, While, and Index-Based Iteration

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Comments

No comments to show.

Archives

Categories

About Me

Sam Doe

Frequent Traveller

Many lives. Many faces. Different crossroads to different places. 🎶 Listen to my new single release “In My Head” Harlem House Shuffle remix