When it is required to convert a tuple into an integer, the lambda function and the 'reduce' function can be used.
Anonymous function is a function which is defined without a name. The reduce function takes two parameters- a function and a sequence, where it applies the function to all the elements of the list/sequence. It is present in the 'functools' module.
In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.
Below is a demonstration of the same −
Example
import functools my_tuple_1 = (23, 45, 12, 56, 78, 0) print("The first tuple is : ") print(my_tuple_1) my_result = functools.reduce(lambda sub, elem: sub * 10 + elem, my_tuple_1) print("After converting tuple to integer, it is ") print(my_result)
Output
The first tuple is : (23, 45, 12, 56, 78, 0) After converting tuple to integer, it is 2768380
Explanation
- The required packages are downloaded.
- A tuple is defined, and is displayed on the console.
- The reduce function is used, to which the lambda, and the tuple are passed as arguments.
- The lambda function multiples every element in the tuple with 10 and adds the previous element to it.
- This operation's data is stored in a variable.
- This variable is the output that is displayed on the console.