Tuple Packing and Unpacking in Python 🎯

beginner
24 min

Tuple Packing and Unpacking in Python 🎯

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!

What is a Tuple? 📝

A tuple is a collection of ordered, immutable (can't be changed) elements. Tuples are defined using parentheses ().

python
my_tuple = (1, "apple", 3.14)

Understanding Tuple Packing 💡

Tuple packing refers to the process of grouping multiple variables together and assigning them to a tuple.

python
# Variables x = 1 y = "apple" z = 3.14 # Packing my_tuple = (x, y, z)

Tuple Unpacking 💡

Tuple unpacking is the reverse process of packing. It involves extracting the elements of a tuple and assigning them to separate variables.

python
# Tuple my_tuple = (1, "apple", 3.14) # Unpacking x, y, z = my_tuple

Why is it Useful? 💡

Packing and unpacking tuples are extremely useful when dealing with multiple variables or values. They help in keeping your code clean and easy to read.

Practical Application 🎯

Let's see a practical example of packing and unpacking in a real-world scenario.

python
# 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)

Quiz 🎯

Quick Quiz
Question 1 of 1

What does tuple unpacking do?

Advanced Tuple Unpacking 💡

You can also unpack multiple tuples or elements of different types in the same line.

python
# 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)

Quiz 🎯

Quick Quiz
Question 1 of 1

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! 🎯