Welcome to another exciting lesson on Python! Today, we're diving into the world of Tuples and learning about an essential feature called Tuple Packing and Unpacking. Let's get started!
A tuple is a collection of ordered, immutable (can't be changed) elements. Tuples are defined using parentheses ().
my_tuple = (1, "apple", 3.14)Tuple packing refers to the process of grouping multiple variables together and assigning them to a tuple.
# Variables
x = 1
y = "apple"
z = 3.14
# Packing
my_tuple = (x, y, z)Tuple unpacking is the reverse process of packing. It involves extracting the elements of a tuple and assigning them to separate variables.
# Tuple
my_tuple = (1, "apple", 3.14)
# Unpacking
x, y, z = my_tuplePacking and unpacking tuples are extremely useful when dealing with multiple variables or values. They help in keeping your code clean and easy to read.
Let's see a practical example of packing and unpacking in a real-world scenario.
# Function that returns a tuple
def get_data():
return (1, "John Doe", 25)
# Packing
data = get_data()
# Unpacking
id, name, age = data
print("Name: ", name)
print("Age: ", age)What does tuple unpacking do?
You can also unpack multiple tuples or elements of different types in the same line.
# Tuple 1
t1 = (1, "apple", 3.14)
# Tuple 2
t2 = ("orange", 2.71)
# Unpacking multiple tuples
id1, fruit1, price1, id2, fruit2, price2 = t1, t2
print("First ID: ", id1)
print("First Fruit: ", fruit1)
print("First Price: ", price1)
print("Second ID: ", id2)
print("Second Fruit: ", fruit2)
print("Second Price: ", price2)Which of the following is a correct way to unpack two tuples?
That's all for this lesson on Tuple Packing and Unpacking in Python! Keep practicing and stay tuned for more exciting lessons! 🎯