In Python, Tuple unpacking is a feature that allows us to assign values to multiple variables in a single statement. It works by unpacking a sequence (e.g., a tuple, list, or string) into individual variables. Unpacking is not limited to tuples, you can also use it to unpack lists, strings, and other iterable objects. Unpacking is a powerful feature in Python that can make your code more concise and readable.
You can unpack tuples in Python by using many ways, for example, using the *
unpacking, dictionary
, lambda
, and list comprehension
. In this article, I will explain tuple unpacking by using all these methods with examples.
Related: In Python, you can also unpack the list.
1. Quick Examples of Tuple Unpacking
If you are in a hurry, below are some quick examples of Python tuple unpacking.
# Quick examples of tuple unpacking
# Example 1: Using * unpacking method
tuples = ('Spark', 'Python', 'pandas', 'Java')
list1 = [*tuples,]
# Example 2: Unpacking tuples as arguments
def technology(courses, fees, duration):
print(courses)
print(fees)
print(duration)
tuples = ('Python', 25000, '50days')
technology(*tuples)
# Example 3: Unpacking tuples as a dictionary
tuples = ('Python', '50days', 25000)
dictionary = dict(zip(('courses', 'duration', 'fees'), tuples))
# Example 4: Unpacking tuples as a dictionary object
tuples = ('Python', '50days', 25000)
dictionary = {}
dictionary['courses'],dictionary['duration'],dictionary['fees'] = tuples
# Example 5: Unpacking tuples using lambda function
tuples = (5, 10)
result = (lambda x,y: x + y)(*tuples)
# Example 6: Unpacking nested tuples
# Using list comprehension
nested_tuple = ((2, 4), (6, 8), (10, 12))
result = [x + y for x, y in nested_tuple]
# Example 7: Using list comprehension
tuples = ((1, 3, 5), (7, 9, 11), (13, 15, 17))
result = [(x,y,z) for x,y,z in tuples]
2. Using * Unpacking Method
You can use unpack operator * on a tuple to extract the individual elements from a tuple and assign its elements to a list by enclosing the tuple in square brackets []
and separating the elements with commas
. For example, use the *
operator to unpack the elements of the tuples
and assign them to the list list1
. The resulting list contains the same elements as the original tuple, in the same order.
# Using * unpacking method
tuples = ('Spark', 'Python', 'pandas', 'Java')
# convert tuple into list
list1 = [*tuples,]
print(list1)
# Output
# ['Spark', 'Python', 'pandas', 'Java']
3. Unpacking Tuple as Arguments
You can unpack tuple and pass the elements of a tuple as arguments to a function in Python. This is a convenient way to pass multiple arguments to a function without having to manually specify each argument.
For example, In the below code snippet we define a function technology
that takes three arguments courses
, fees
, and duration
. And, create a tuple tuples
with three elements and use tuple unpacking with the *
operator to pass the elements of the tuple as arguments to the function.
# Unpacking tuple as arguments
def technology(courses, fees, duration):
print(courses)
print(fees)
print(duration)
tuples = ('Python', 25000, '50days')
technology(*tuples)
# Output
# Python
# 25000
# 50days
4. Unpacking Tuples as Dictionary
To unpack a tuple as a dictionary, you can use the dict()
constructor along with the zip()
function to create a dictionary from the key-value pairs generated by the zip()
function.
For example, let’s take tuple with three elements, and create a dictionary dictionary
with keys courses
, fees
, and duration
corresponding to the elements of the tuple. First, use the zip()
function to create a sequence of key-value pairs by matching each element of the tuple with a corresponding key. Then, you use the dict()
constructor to convert the sequence of key-value pairs into a dictionary.
# Unpacking tuples as dictionary
tuples = ('Python', '50days', 25000)
dictionary = dict(zip(('courses', 'duration', 'fees'), tuples))
print(dictionary)
# Output
# {'courses': 'Python', 'duration': '50days', 'fees': 25000}
Follow the other example of unpacking a tuple as a dictionary object.
# Unpacking tuples as dictionary object
tuples = ('Python', '50days', 25000)
dictionary = {}
dictionary['courses'],dictionary['duration'],dictionary['fees'] = tuples
print(dictionary)
# Output
# {'courses': 'Python', 'duration': '50days', 'fees': 25000}
5. Unpacking Tuples Using Lambda Function
You can also use a lambda
function to unpack tuples in Python. For example, you define a lambda function that takes two arguments x
and y
, and returns their sum. Use the *
operator to unpack the tuple and pass their contents as arguments to the lambda
function. The result is the sum of the two values in the tuple, which is 15
.
# Unpacking tuples using lambda function
tuples = (5, 10)
result = (lambda x,y: x + y)(*tuples)
print(result)
# Output
# 15
6. Unpacking Nested Tuples Using List Comprehension
You can also use list comprehension to unpack nested tuples in Python. For example, create a nested tuple with three tuples, each containing two values. You can use a list comprehension to iterate over each tuple in the nested_tuple
, unpack the values using the syntax x
, and y
, and add them together to create a new list with the resulting values.
# Unpacking nested tuples
# Using list comprehension
nested_tuple = ((2, 4), (6, 8), (10, 12))
result = [x + y for x, y in nested_tuple]
print(result)
# Output
# [6, 14, 22]
Follow the other example of a list comprehension to unpack nested tuples in Python.
# Unpacking nested tuples
# Using list comprehension
tuples = ((1, 3, 5), (7, 9, 11), (13, 15, 17))
result = [(x,y,z) for x,y,z in tuples]
print(result)
# Output
# [(1, 3, 5), (7, 9, 11), (13, 15, 17)]
Conclusion
In this article, I have explained python tuple unpacking by using *
unpacking, dictionary
, lambda
, and list comprehension
with examples.
Happy Learning !!
Related Articles
- Python Tuple Access with Example
- Add Element to Tuple in Python
- Add Elements of Tuples in Python
- Append Element to a Tuple in Python
- Python Empty Tuple with Examples
- Python Tuple Slice with Examples
- Python Tuple Length with Example
- How to Sort List of Tuples in Python
- Remove Last Element from Tuple in Python
- Tuple as Dictionary Key in Python