Skip to Content

Python Tuple to Integer

In this tutorial, we will look at how to convert a tuple to an integer in Python with the help of some examples.

Depending on what exactly you want, there can be several ways to convert a tuple to an integer. For example – If you want to convert the tuple (1,2,3) to the integer 123, you can do so by concatenating the digits as strings into a single string and then convert it to an integer.

Convert tuple to an integer in Python

Let’s look at an example.

# create a tuple 
t = (1, 2, 3)
# tuple to integer
num = int("".join(map(str, t)))
print(num)

Output:

123

Here we create a single integer from a tuple of integers. We use the map() function to convert each element in the tuple to a string. Then we use the string join() function to concatenate the string digits. Finally, we convert the resulting string to an integer using the int() function.

Alternatively, you can also use a list comprehension instead of the map() function to convert each element to a string.

# create a tuple 
t = (1, 2, 3)
# tuple to integer
num = int("".join([str(i) for i in t]))
print(num)

Output:

123

We get the same result as above.

If, on the other hand, you just want to unpack the elements of a tuple to different variables, you can use the assignment operator =.

# create a tuple
person = ("Jim", 23)
# unpack the tuple 
name, age = person
print(name)
print(age)

Output:

Jim
23

Here, we unpack the tuple ("Jim", 23) such that the variable name stores the first element, "Jim" and the variable age stores the second element, "23".

If you’re looking to convert a particular element from a tuple to an integer, you can do simply use the Python built-in int() function on the respective element.

For example, if you have a tuple of string digits and you want to convert the first element to an integer.

# create a tuple 
t = ("7", "11")
# convert first tuple element to int
num = int(t[0])
print(num)
print(type(num))

Output:

7
<class 'int'>

Here we access the first element using its index and then pass it to the int() function. We get the resulting value as an integer.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush

    Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.