Tuples Packing and Unpacking in Python

In this Python article we want to learn about Tuples Packing and Unpacking in Python, in Python tuple is a sequence data type that is similar to a list but is immutable, it means that tuples cannot be modified once it is created. one of the powerful features of tuples in Python is the ability to pack and unpack them. in this article we want to talk what tuples packing and unpacking are and how they can be used in Python.

 

 

Tuples Packing and Unpacking in Python

Tuple packing is the process of assigning values to a tuple. this is done by enclosing the values in parentheses separated by commas. for example to create a tuple that stores the first name, last name and age of a person, you can do it like this.

 

 

This will be the result

Tuples Packing and Unpacking in Python
Tuples Packing and Unpacking 

 

 

Python tuples unpacking is the process of extracting values from a tuple and assigning them to variables. this is done by assigning the tuple to the variables separated by commas. for example to unpack the values from the person tuple you can do it like this.

 

 

 

This will be the result

Tuples Packing and Unpacking in Python
Tuples Packing and Unpacking in Python

 

 

Tuple packing and unpacking can also be used in function arguments and return values. for example let’s say you have a function that calculates the area and perimeter of rectangle:

In this example rectangle_dimensions function takes two arguments length and width, calculates the area and perimeter of a rectangle using these values and returns a tuple containing the area and perimeter. for calling this function and unpack the values from the returned tuple you can do it like this:

 

In this example we have called the rectangle_dimensions function with the arguments 5 and 10. this function calculates the area and perimeter of a rectangle with length 5 and width 10 and returns a tuple containing the area and perimeter. after that we have unpacked the values from the returned tuple and assigned them to the variables area and perimeter.

 

 

This will be the result

Tuples Packing and Unpacking in Python
Tuples Packing and Unpacking in Python

 

 

 

Learn More on Python Tuples

Leave a Comment