
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Unpacking tuple of lists in Python
When it is required to unpack a tuple of list, the 'reduce' method can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A tuple of list contains multiple lists, which are enclosed in '(' and ')'.
The 'reduce' method is used to apply a specific method (that is passed as an argument to it) to all the values in the iterable. This method is present in the 'functools' module.
Below is a demonstration for the same −
Example
from functools import reduce import operator def unpack_tuple(my_tup): return (reduce(operator.add, my_tup)) my_tuple = (['h', 'jane'], ['m', 'may']) print("The tuple of list is") print(my_tuple) print("After unpacking, it is") print(unpack_tuple(my_tuple))
Output
The tuple of list is (['h', 'jane'], ['m', 'may']) After unpacking, it is ['h', 'jane', 'm', 'may']
Explanation
- The required packages are imported into the environment.
- A function named 'unpack_tuple' is defined that takes a tuple as parameter.
- It uses the 'reduce' method, and calls the 'add' method on all elements inside the tuple.
- Now, a tuple of list is defined, and is displayed on the console.
- This function is called by passing the tuple of list as parameter.
- This operation's data is stored in a variable.
- This variable is the output that is displayed on the console.
- Related Articles
- Unpacking a Tuple in Python
- What is tuple unpacking in Python?
- Sort lists in tuple in Python
- Python to Find number of lists in a tuple
- Convert a list into tuple of lists in Python
- Python - Ways to iterate tuple list of lists
- Packing and Unpacking Arguments in Python?
- Flatten tuple of List to tuple in Python
- Accessing Values of Lists in Python
- Updating Lists in Python
- Python - Intersection of multiple lists
- Intersection of Two Linked Lists in Python
- Modulo of tuple elements in Python
- Raise elements of tuple as power to another tuple in Python
- Custom Multiplication in list of lists in Python

Advertisements