Unpacking tuple of lists in Python

PythonServer Side ProgrammingProgramming

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

Live Demo

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.
raja
Published on 13-Mar-2021 05:35:27
Advertisements