Open In App

Unpacking a Tuple in Python

Last Updated : 24 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program.

Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable.

Example 1 

Python3




# Program to understand about
# packing and unpacking in Python
 
# this lines PACKS values
# into variable a
a = ("MNNIT Allahabad", 5000, "Engineering"
 
# this lines UNPACKS values
# of variable a
(college, student, type_ofcollege) =
 
# print college name
print(college)
 
# print no of student
print(student)
 
# print type of college
print(type_ofcollege)


Output: 

MNNIT Allahabad
5000
Engineering

 

NOTE : In unpacking of tuple number of variables on left-hand side should be equal to number of values in given tuple a.
Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that there can be many number of arguments in place of (*args) in python. All values will be assigned to every variable on the left-hand side and all remaining values will be assigned to *args .For better understanding consider the following code. 

Example 2 

Python3




# Python3 code to study about
# unpacking python tuple using *
 
# first and last will be assigned to x and z
# remaining will be assigned to y
x, *y, z = (10, "Geeks ", " for ", "Geeks ", 50)
 
# print details
print(x)
print(y)
print(z)
 
# first and second will be assigned to x and y
# remaining will be assigned to z
x, y, *z = (10, "Geeks ", " for ", "Geeks ", 50)
print(x)
print(y)
print(z)


Output: 

10
['Geeks ', ' for ', 'Geeks ']
50
10
Geeks 
[' for ', 'Geeks ', 50]

 

In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable. Consider the following code for better understanding. 

Example 3 : 

Python3




# Python3 code to study about
# unpacking python tuple using function
 
# function takes normal arguments
# and multiply them
def result(x, y):
    return x * y
# function with normal variables
print (result(10, 100))
 
# A tuple is created
z = (10, 100)
 
# Tuple is passed
# function unpacked them
 
print (result(*z))


Output: 

1000
1000

 



Previous Article
Next Article

Similar Reads

Python | Unpacking tuple of lists
Given a tuple of lists, write a Python program to unpack the elements of the lists that are packed inside the given tuple. Examples: Input : (['a', 'apple'], ['b', 'ball']) Output : ['a', 'apple', 'b', 'ball'] Input : ([1, 'sam', 75], [2, 'bob', 39], [3, 'Kate', 87]) Output : [1, 'sam', 75, 2, 'bob', 39, 3, 'Kate', 87] Approach #1 : Using reduce()
3 min read
Python | Unpacking dictionary keys into tuple
In certain cases, we might come into a problem in which we require to unpack dictionary keys to tuples. This kind of problem can occur in cases we are just concerned about the keys of dictionaries and wish to have a tuple of them. Let's discuss certain ways in which this task can be performed in Python. Example Input: {'Welcome': 1, 'to': 2, 'GFG':
4 min read
Python | Unpacking nested tuples
Sometimes, while working with Python list of tuples, we can have a problem in which we require to unpack the packed tuples. This can have a possible application in web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension This task can be performed using list comprehension in which we iter
6 min read
Python - Unpacking Values in Strings
Given a dictionary, unpack its values into a string. Input : test_str = "First value is {} Second is {}", test_dict = {3 : "Gfg", 9 : "Best"} Output : First value is Gfg Second is Best Explanation : After substitution, we get Gfg and Best as values. Input : test_str = "First value is {} Second is {}", test_dict = {3 : "G", 9 : "f"} Output : First v
3 min read
Unpacking arguments in Python
If you have used Python even for a few days now, you probably know about unpacking tuples. Well for starter, you can unpack tuples or lists to separate variables but that not it. There is a lot more to unpack in Python. Unpacking without storing the values: You might encounter a situation where you might not need all the values from a tuple but you
3 min read
Packing and Unpacking Arguments in Python
We use two operators * (for tuples) and ** (for dictionaries). Background Consider a situation where we have a function that receives four arguments. We want to make a call to this function and we have a list of size 4 with us that has all arguments for the function. If we simply pass a list to the function, the call doesn't work. C/C++ Code # A Py
5 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg