Explain the concept of tuple packing and unpacking in Python with examples.

Explain the concept of tuple packing and unpacking in Python with examples.

Tuple packing and unpacking are important ideas in Python. They let you assign and get multiple values quickly. Here are five examples to explain:

Tuple Packing:

Tuple packing occurs when you assign multiple values to a single tuple variable. Python automatically packs these values into a tuple.

Example 1:

# Tuple packing
my_tuple = 10, 20, 30
print(my_tuple)  # Output: (10, 20, 30)

Example 2:

# Tuple packing with different data types
mixed_tuple = 'apple', 3, True
print(mixed_tuple)  # Output: ('apple', 3, True)

Tuple Unpacking:

Tuple unpacking involves assigning the elements of a tuple to multiple variables simultaneously. It allows you to extract individual values from a tuple easily.

Example 3:

# Tuple unpacking
x, y, z = my_tuple
print(x)  # Output: 10
print(y)  # Output: 20
print(z)  # Output: 30

Example 4:

# Tuple unpacking with fewer variables than elements
first, *rest = my_tuple
print(first)  # Output: 10
print(rest)   # Output: [20, 30]

In this example, *rest collects the remaining elements into a list.

Example 5:

# Swapping variables using tuple unpacking
a = 5
b = 10
a, b = b, a
print("a =", a)  # Output: 10
print("b =", b)  # Output: 5

This demonstrates a common idiom in Python to swap the values of two variables without needing a temporary variable.

In each of these examples, tuple packing and unpacking provide a concise and powerful way to work with multiple values in Python.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!