Q:

Python program to convert tuple to integer

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Converting Tuple to Integer

In this program, we are given a tuple consisting of digits. We need to create a Python program to convert the tuple to an integer.

Input:
(7, 1, 6, 9)

Output:
7169

For this, we will iterate through the tuple and create a number using the digits in the tuple.

This can be done using the built-in functions of the python programming language.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method is using the lambda function that converts the given tuple into a number. And then use the reduce method to get the final output.

# Python program to convert tuple to integer

import functools

# Initializing and printing the tuple
myTuple = (7, 2, 9, 3)
print("The elements of the tuple are " + str(myTuple))

# Converting tuple to number 
num = functools.reduce(lambda N, digit: N * 10 + digit, myTuple)

# Printing result
print("The integer created from the tuple is " + str(num))

Output:

The elements of the tuple are (7, 2, 9, 3)
The integer created from the tuple is 7293

Method 2:

Another method to solve the problem is by mapping each element of the tuple and concatenating them as strings which will produce the integer value in string form. This string then can be easily converted to an integer using the int() method.

# Python program to convert tuple to integer

# Initializing and printing the tuple
myTuple = (7, 2, 9, 3)
print("The elements of the tuple are " + str(myTuple))

# Converting tuple to number 
num = int(''.join(map(str, myTuple)))

# Printing result
print("The integer created from the tuple is " + str(num))

Output:

The elements of the tuple are (7, 2, 9, 3)
The integer created from the tuple is 7293

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to check if the element is present ... >>
<< Python program to perform XOR operation on tuples...