Unpack Tuples

Unpacking a tuple means assigning the elements of a tuple to multiple variables at once. This is a convenient way to extract values from a tuple.

Unpacking Example

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

# Unpack the tuple into variables
(fruit1, fruit2, fruit3) = fruits

print(fruit1)  # Output: apple
print(fruit2)  # Output: banana
print(fruit3)  # Output: cherry

Unpacking with * Operator

You can use the * operator to assign the remaining values to a list:

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

# Unpack with *
(fruit1, *others) = fruits

print(fruit1)  # Output: apple
print(others)  # Output: ["banana", "cherry", "date"]