- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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))
The tuple of list is (['h', 'jane'], ['m', 'may']) After unpacking, it is ['h', 'jane', 'm', 'may']
- 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.
- Unpacking a Tuple in Python
- What is tuple unpacking in Python?
- Sort lists in tuple in Python
- Python - Ways to iterate tuple list of lists
- Convert a list into tuple of lists in Python
- Python to Find number of lists in a tuple
- Packing and Unpacking Arguments in Python?
- Flatten tuple of List to tuple in Python
- Accessing Values of Lists in Python
- Python - Intersection of multiple lists
- Modulo of tuple elements in Python
- Intersection of Two Linked Lists in Python
- Updating Lists in Python
- Raise elements of tuple as power to another tuple in Python
- Custom Multiplication in list of lists in Python