In Python, tuples are immutable sequences, often used to store related pieces of data. Packing and unpacking are two essential processes that allow you to work with tuples efficiently in Python.
In our previous article Concatenate Tuples in Python, we introduced the packing process where multiple tuple elements were combined into a single tuple. This article delves deeper into the packing & unpacking of tuples in Python. We will explore ways for packing and unpacking of tuples in Python using asterisk *
. We will also explore example programs and interview questions related to packing and unpacking of tuples in Python.
Packing and Unpacking of Tuples in Python
Packing a tuple refers to the process of grouping multiple values together into a single tuple.
tuple_object = (value_1, value_2, value_3)
Unpacking a tuple means extracting the values in the tuple to individual variables. The number of variables on the left-hand side must match the number of elements in the tuple.
variable_1, variable_2, variable_3 = tuple_object
Python uses the following operators for packing and unpacking of collection elements:
- Asterisk
*
is used with lists & tuples - Double asterisk
**
is used with dictionaries
Packing and unpacking operations are very useful for:
- Converting tuple elements into separate variables.
- Passing tuple elements as function arguments.
Let’s see different ways to perform packing and unpacking of tuples in Python:
- Unpacking Tuple Elements Without Asterisk *
- Error: Unpacking Tuple Without Asterisk (*)
- Unpacking Tuples Using Asterisk (*)
- Error – Unpacking Tuple Using Asterisk (*) Multiple Variables
- Unpacking Tuples with Function Arguments
Unpacking Tuple Elements Without Asterisk *
Unpacking can be performed without using an asterisk (*), only if the number of elements in the tuple are equal to the number of variables to extract value. For example => tuple_object = (value_1, value_2, value_3)
# unpacking tuple elements - without astrisk (*)
print("unpacking tuple elements - without astrisk (*)")
courses = ("AWS", "Azure", "Python")
(c1, c2, c3) = courses # Unpacking tuple elements into variable values
print("course 1 - ", c1)
print("course 2 - ", c2)
print("course 3 - ", c3)
# Output
# unpacking tuple elements - without astrisk (*)
# course 1 - AWS
# course 2 - Azure
# course 3 - Python
In this program, we have defined a tuple ("AWS", "Azure", "Python")
which is referenced by a variable name courses
. This tuple has 3 elements. During the unpacking process (c1, c2, c3) = courses
, we are passing three variables (c1, c2, c3)
in parenthesis and assigning it with tuple courses
. Each element of tuple will be assigned to each variable in the same order.
From the program output, variable c1
, c2
, c3
are assigned with values AWS
, Azure
, Python
respectively. Value assigned to each variable is in the same order as elements were in the tuple.
Error: Unpacking Tuple Without Asterisk (*)
If we unpack the tuple without asterisk *
and the tuple has more or fewer elements than the number of variables, then it will raise a ValueError
.
Error – Unpacking Tuple Without Asterisk (*) with Extra Elements
Unpacking tuple without using an asterisk (*), we will get an error when number of elements in tuple are more than number of variables passed.
# Error - Unpacking Tuple Without Asterisk (*) with Extra Elements
print("Error - unpacking tuple without astrisk (*) - extra elements")
courses = ("Python", "AWS", "Azure", "Java") # tuple has 4 elements
(a1, a2, a3) = courses # unpacking - 3 variables passed, tuple has 4 elements
# Output
# Traceback (most recent call last):
# File "D:\unpacking-tuple.py", line 14, in <module>
# (a1, a2, a3) = courses
# ^^^^^^^^^^^^
# ValueError: too many values to unpack (expected 3)
Defined tuple courses = ("Python", "AWS", "Azure", "Java")
has 4 elements. During the unpacking process (a1, a2, a3) = courses
, we are passing 3 variables in parenthesis and assigning it with tuple. This will raise an error because the number of elements in tuple and number of variables passed are not equal.
From the program output, error is raised – ValueError - too many values to unpack (expected 3)
, because tuple has 4 elements and we are trying to unpack them into 3 variables.
Error – Unpacking Tuple Without Asterisk (*) with Fewer Elements
Unpacking tuple without using an asterisk (*), we will get an error when number of elements in tuple are fewer than number of variables passed.
# Error - Unpacking Tuple Without Asterisk (*) with Fewer Elements
print("Error - unpacking tuple with less elements")
courses = ("Python", "NumPy") # tuple has 2 elements
(a1, a2, a3) = courses # unpacking - 3 variables passed, tuple has 2 elements
# Output
# Error - unpacking tuple with less elements
# Traceback (most recent call last):
# File "D:\unpacking-tuple.py", line 22, in <module>
# (a1, a2, a3) = courses
# ^^^^^^^^^^^^
# ValueError: not enough values to unpack (expected 3, got 2)
Defined tuple courses = ("Python", "NumPy")
has 2 elements. During the unpacking process (a1, a2, a3) = courses
, we are passing 3 variables in parenthesis and assigning it with tuple. This will raise an error because the number of elements in tuple and number of variables passed are not equal.
From the program output, error is raised – ValueError - not enough values to unpack (expected 3, got 2)
Unpacking Tuples Using Asterisk (*)
The asterisk (*
) allows for dynamic unpacking. Following are properties of using asterisk (*) to unpack tuples:
- Using asterisk (
*
), we can have more number of elements in tuple compare to number of variables passed. - Using asterisk (
*
) will not work if we have less number of elements in tuple and more variable are passed. - We can use asterisk (
*
) with any one of the given variables - Variable with asterisk (
*
) will take extra elements as list from the given tuple and other elements will be assigned to other variables. - Asterisk (
*
) variable value will be returned as a list, either it is unpacked from tuple or list.
Unpacking Tuples Using Asterisk (*) with First Variable
# Unpacking Tuples Using Asterisk (*) with First Variable
print("unpacking tuple - using asterisk* first variable")
courses = ("NumPy", "Pandas", "Python", "Java", "Data Science", "Machine Learning")
(*c1, c2, c3) = courses # unpacking, astrisk (*) used with first variable
print("course tuple c1 - ", c1)
print("course c2 - ", c2)
print("course c3 - ", c3)
# Output
# unpacking tuple - using asterisk* first variable
# course tuple c1 - ['NumPy', 'Pandas', 'Python', 'Java']
# course c2 - Data Science
# course c3 - Machine Learning
Defined tuple courses
has 6 elements. During the unpacking process (*c1, c2, c3) = courses
, we are passing 3 variables. Variable *c1
is with asterisk (*
). Tuple has more number of elements compared to number of variables passed. Variable c2
and c3
will take the last two elements in order from the tuple and remaining elements will be assigned to variable c1
as a list.
From the program output, variable c2
and c3
are assigned last two elements in order from the tuple and c1
is the list with remaining elements.
Unpacking Tuples Using Asterisk (*) with in-between Variable
# Unpacking Tuples Using Asterisk (*) with in-between Variable
print("unpacking tuple - using asterisk* in between")
courses = ("NumPy", "Pandas", "Python", "Java", "Data Science", "Machine Learning")
(c1, *c2, c3) = courses # unpacking, astrisk (*) used with in-between variable
print("course c1 - ", c1)
print("course tuple c2 - ", c2)
print("course c3 - ", c3)
# Output
# unpacking tuple - using asterisk* in between
# course c1 - NumPy
# course tuple c2 - ['Pandas', 'Python', 'Java', 'Data Science']
# course c3 - Machine Learning
Again defined tuple courses
has 6 elements. During the unpacking process (c1, *c2, c3) = courses
, we are passing 3 variables. Variable *c2
is with asterisk (*
). Tuple has more number of elements compared to number of variables passed. Variable c1
will be assigned first element of tuple and c3
will be assigned last element of tuple and remaining in-between elements will be assigned to variable c2
as a list.
Unpacking Tuples Using Asterisk (*) with Last Variable
# Unpacking Tuples Using Asterisk (*) with Last Variable
print("unpacking tuple - using asterisk* at last")
courses = ("NumPy", "Pandas", "Python", "Java", "Data Science", "Machine Learning")
(c1, c2, *c3) = courses # unpacking, astrisk (*) used with last variable
print("course c1 - ", c1)
print("course c2 - ", c2)
print("course tuple c3 - ", c3)
# Output
# unpacking tuple - using asterisk* at last
# course c1 - NumPy
# course c2 - Pandas
# course tuple c3 - ['Python', 'Java', 'Data Science', 'Machine Learning']
Again defined tuple courses
has 6 elements. During the unpacking process (c1, c2, *c3) = courses
, we are passing 3 variables. Variable *c3
is with asterisk (*
). Tuple has more number of elements compared to number of variables passed. Variable c1
will be assigned first element of tuple and c2
will be assigned second element of tuple and remaining last elements will be assigned to variable c3
as a list.
Error – Unpacking Tuple Using Asterisk (*) Multiple Variables
If we use asterisk (*) with multiple variables, then SyntaxError
will be raised.
# Error - unpacking tuple - using asterisk* multiple times
print("Error - unpacking tuple - using asterisk* multiple times")
courses = ("NumPy", "Pandas", "Python", "Java", "Data Science", "Machine Learning")
try:
(c1, *c2, *c3) = courses # unpacking, astrisk (*) used with multiple variables
except SyntaxError as err:
print("error", err)
# Output
# File "D:\unpacking-tuple.py", line 64
# (c1, *c2, *c3) = courses
# ^^^^^^^^^^^^^^
# SyntaxError: multiple starred expressions in assignment
During the unpacking process (c1, *c2, *c3) = courses
, we are passing 3 variables. Variables *c2
& *c3
are with asterisk (*
). Because of multiple variables with asterisk(*
), program will not know which variable to assigned the remaining elements. That is why it will raise an error – SyntaxError: multiple starred expressions in assignment
.
Unpacking Tuples with Function Arguments
In previous sections, we have seen how unpacking process works and how we can use asterisk (*
) to unpack multiple elements of a tuple. Generally, unpacking process is used to pass the tuple elements as an argument to a function and its elements are unpacked to assign values to function parameters. Lets understand this with program.
In this program, we have defined a function fun_print_arguments(k, l, m, n)
with 4 arguments and a tuple number_tuple
with 5 elements.
# Unpacking tuple with function arguments
print("Unpacking tuple with function arguments\n")
def fun_print_arguments(k, l, m, n): # Definition of function
print("Number k - ", k)
print("Number l - ", l)
print("Number m - ", m)
print("Number n - ", n)
number_tuple = (30, 40, 50, 60, 70)
We will test three scenarios with this program:
Scenario 1: Tuple is passed without asterisk (*
) as an argument to the function. This will raise an error.
# Tuple is passed without asterisk as an argument to the function will raise an error
print("\nPassing tuple directly to function will give an error")
try:
fun_print_arguments(number_tuple)
except TypeError as err:
print("error", err)
In this scenario, we are calling function fun_print_arguments(number_tuple)
and passing the tuple without asterisk (*
) as an argument. Passing tuple without asterisk (*
) will not unpack its elements and will be considered as a single argument passed. Program will raise an error – fun_print_arguments() missing 3 required positional arguments: 'l', 'm', and 'n'
Scenario 2: Tuple with more number of elements (than the number of parameters of the function) is passed as an argument to the function. This will raise an error.
# Tuple with more number of elements than function parameters will raise an error
print("\nPassing more elements than function arguments will give an error")
try:
fun_print_arguments(*number_tuple) # passing tuple has more number of elements
except TypeError as err:
print("error", err)
In second scenario, we are calling function fun_print_arguments(*number_tuple)
and passing the tuple with asterisk (*
) as an argument. Tuple has 5 elements in it but function requires 4 arguments. Passed tuple will be unpacked with 5 elements but will fail to assign all elements to variables. The program will raise an error – fun_print_arguments() takes 4 positional arguments but 5 were given
.
Scenario 3: Tuple with exactly same number of elements (as number of parameters of the function) is passed as an argument to the function.
# Passing tuple with same number elements as function arguments
print("\nPassing same number elements as function arguments")
number_tuple = (30, 40, 50, 60)
fun_print_arguments(*number_tuple) # passed tuple has same number of elements
In third scenario, we are calling function fun_print_arguments(*number_tuple)
and passing the tuple with astrisk (*
) as an argument. Tuple has 4 elements and function also requires 4 arguments. Passed tuple will be unpacked with 4 elements and all elements will be assigned to variables. Successfully print the assigned values to variables.
Complete Program Output (including all sections)
Unpacking tuple with function arguments
Passing tuple directly to function will give an error
error fun_print_arguments() missing 3 required positional arguments: 'l', 'm', and 'n'
Passing more elements than function arguments will give an error
error fun_print_arguments() takes 4 positional arguments but 5 were given
Passing same number elements as function arguments
Number k - 30
Number l - 40
Number m - 50
Number n - 60
Conclusion
Mastering the packing and unpacking of tuples in Python enhances your ability to manage and manipulate collections of data effectively. Whether it’s packing values into a tuple for easier handling or unpacking them for specific use, understanding how to do so with and without the asterisk (*
) is crucial.
Unpacking tuples without the asterisk is straightforward when the number of elements matches the number of variables, while using the asterisk allows you to collect extra elements dynamically into a list or other data structures. However, it’s important to avoid common errors, such as unpacking a tuple without the proper number of variables or using the asterisk with multiple variables incorrectly.
Additionally, using tuple unpacking in function arguments enables you to pass multiple related values cleanly and efficiently, making your code more readable and concise. Overall, tuple unpacking is a versatile tool in Python that simplifies data manipulation and function handling, providing greater flexibility and clarity in your code.
Code snippets and programs related to Concatenate Tuples in Python, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.
Interview Questions & Answers
Q: How to use tuple unpacking to swap the values of two variables?
Generally, values of two variables are swapped using a temporary variable. Tuple unpacking provides a concise way to swap the values of two variables without using a temporary variable. The values of two variables can be swapped in a single line using tuple unpacking.
a = 55
b = 105
# Swapping using tuple unpacking
a, b = b, a
print(a, b) # After swap => a = 105, b = 55
Using tuple unpacking multiple variable values can be changed or swapped in single line.
Q: How can we unpack nested tuples?
To unpack nested tuple, we have to match the structure of the tuple during unpacking.
nested_tuple = (12, (22, 32), 24)
a, (b, c), d = nested_tuple
print(a, b, c, d) # a = 12, b = 22, c = 32, d = 24
Q: What is the difference between tuple unpacking and list unpacking?
Tuple unpacking and list unpacking works similarly, but tuples are immutable, whereas lists are mutable. This means once a tuple is created, it cannot be changed, whereas the contents of a list can be modified.
number_list = [12, 22, 34]
number_tuple = (12, 22, 34)
a, b, c = number_list # a = 12, b = 22, c = 34
x, y, z = number_tuple # x = 12, y = 22, z = 34
Q: How does tuple unpacking work with loops?
Tuple unpacking can be used in a loop to directly access the elements of each tuple in a sequence.
coordinates = [(11, 12), (33, 34), (56, 66)]
for x, y in coordinates:
print(f"x: {x}, y: {y}")
# Following values will be printed:
# x: 11, y: 12
# x: 33, y: 34
# x: 56, y: 66
Q: What are some common use cases for tuple packing and unpacking?
- Return multiple values from a function – Functions often return tuples to pass multiple values.
def get_course():
return ("Python", "Power BI", "LangChain")
course_1, course_2, course_3 = get_course()
- Swapping values using tuple unpacking =>
var_1, var_2 = var_2, var_1
- Iteration over items in lists or dictionaries – Unpacking elements pairs in loops simplifies code.
for key, value in dict_obj.items():
print(f"{key}: {value}")
Related Topics
- Update List Elements | Modify Elements in Python ListIn Python, elements in a list can be updated or replaced by assigning a new value to an element’s index position. In previous articles, we covered accessing list elements by index, using the list index method to find an element’s index, and appending elements to a list. This article focuses on how to update elements…
- Understanding Lists in Python: A Comprehensive GuideLists in Python List is a core datatype in Python. Lists are sequences used to store elements (collection of data). Lists are similar to Arrays but are of dynamic size. It means the size of the list can be increased or decreased as we add or remove elements from the list. Understanding Python Lists: A…
- Understand the Index Method in Python Tuples: Use Cases, Limitations, and ExamplesElements in the tuple are stored based on their index positions. Python provides the index(arg) method to determine the index position of an element in a tuple. In previous article Access tuple elements by index in Python, we learned about accessing the tuple element at the given index position. In this article we will learn…
- Tuples in Python: Operations, Definition & ExamplesTuples in Python Python tuples is a sequence used to store elements (a collection of data). Similar to arrays and lists, tuples also store elements based on their index and can be accessed based on the index position. Understanding Python Tuples: A Core Datatype Tuples are core data types in Python, alongside list, set, and…
- Slicing of Tuple in Python: Methods, Examples & Interview QuestionsSlicing of a tuple means extracting a part (or slice) of the tuple. In Python, tuple slicing can be done in two primary ways: In previous articles, we learned about Access Tuple Elements by Index in Python, How to Change Elements in a Tuple in Python and How to Remove Elements from a Tuple in Python.…