Friday, July 1, 2022

Python - Unpacking Tuples

# Python can "unpack" tuple items into variables like this:

fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits

# apple
print(green)
# banana
print(yellow)
# cherry
print(red)

print("---")

# This will cause an error because there are
# too many values to unpack
# into only three variables
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
#(green, yellow, red) = fruits

# So use an asterisk * instead

(green, yellow, *red) = fruits

# apple
print(green)
# banana
print(yellow)
# ['cherry', 'strawberry', 'raspberry']
print(red)

# All the remaining variables got shoved into a list called "red"
# <class 'list'>
print(type(red))

(green, *tropic, red) = fruits

print("---")

# apple
print(green)
# You will notice that Python assigned all the values to "tropic"
# except the last one so it matched the number of variables we provided.
# ['banana', 'cherry', 'strawberry']
print(tropic)
# raspberry
print(red)