Python program to convert tuple to integer

In this program, we are given a tuple consisting of digits of a number. We need to create Python program to convert tuple to integer.
Submitted by Shivang Yadav, on December 15, 2021

One common task that we need to perform is the interconversion of collection to some primary data types. Here, we are given a tuple that consists of digits of an integer value. We need to create a Python program to convert tuples to integers.

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

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.

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

Python Tuple Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.