You have a tuple of integers—but you want a single integer. What can you do?
Problem Formulation and Solution Overview
Given a tuple of values.
t = (1, 2, 3)
Goal: Convert the tuple to a single integer value.
t = (1, 2, 3) int(t)
This doesn’t work! Here’s the error message that appears if you try to do this direct conversion from tuple to int:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
In principle, there are two ways of converting a tuple to an integer and avoiding this TypeError:
- Select one of the tuple elements
tuple[i]using tuple indexing of the
i-th tuple element.
- Aggregate the tuple elements to a single integer value, e.g., summing over all tuple elements or combining their string aggregation.
Let’s get a quick overview in our interactive Python shell:
Exercise: Modify method 2 to calculate the average and round to the next integer!
Let’s dive into each of the methods.
Method 1: sum()
The first way of converting a tuple to an integer is to sum up all values. The
sum() function is built-in in Python and you can use it on any iterable:
The syntax is
|Sum over all elements in the |
|(Optional.) The default start value is 0. If you define another start value, the sum of all values in the |
Here’s how you can use the
sum() function to sum over all values in an iterable (such as a tuple):
# Method 1: sum() t = (1, 2, 3) i = sum(t) print(i) # 6
In this case, it calculates 1+2+3=6. You can learn more about the
sum() function on this Finxter blog article.
But what if you want to use all tuple values as digits of a larger integer value?
Method 2: str() + list comprehension + join()
List comprehension is a compact way of creating lists. The simple formula is
[expression + context].
- Expression: What to do with each list element?
- Context: What elements to select? The context consists of an arbitrary number of
You can use it in combination with the
sum() function to calculate the integer 123 from the tuple
(1, 2, 3)—by using the tuple values as digits of the larger integer.
# Method 2: str() + list comprehension + join() t = (1, 2, 3) i = ''.join(str(x) for x in t) print(int(i)) # 123
Well, to be frank, we didn’t even use list comprehension here—the correct term for
str(x) for x in t is “generator expression”. The difference to list comprehension is that it creates a generator instead of a list.
If you like functional programming, you may like the following method:
Method 3: str() + map() + join()
The map() function creates a new iterable from an iterable by applying a function to each element of the original iterable:
Then, you can join all strings together to a big string. After converting the big string to an integer, you’ve successfully merged all tuple integers to a big integer value.
# Method 3: str() + map() + join() t = (1, 2, 3) i = ''.join(map(str, t)) print(i) # 123
There are many details to the
string.join() method. You can read the detailed tutorial on the Finxter blog. Here’s the short version:
string.join(iterable) method concatenates all the string elements in the
iterable (such as a list, string, or tuple) and returns the result as a new string. The
string on which you call it is the delimiter string—and it separates the individual elements. For example,
'-'.join(['hello', 'world']) returns the joined string
Method 4: Multiple Assignments
If you simply want to get multiple integers by assigning the individual tuple values to integer variables, just use the multiple assignment feature:
# Method 4: multiple assignments t = (1, 2, 3) a, b, c = t print(a) print(b) print(c) ''' 1 2 3 '''
c have the values 1, 2, and 3, respectively.
Method 5: Reduce Function
After writing this article, I realized that there’s a fifth way to convert a tuple to an integer value:
To convert a tuple to an integer value, use the
reduce() function from the
functools library in combination with the lambda function to aggregate the elements using any binary aggregator function such as multiplication, addition, subtraction like so:
functools.reduce(lambda aggregate, element: aggregate * element, t)
functools.reduce(lambda aggregate, element: aggregate + element, t)
functools.reduce(lambda aggregate, element: aggregate - element, t)
Here’s a basic example using the multiplication aggregation for starters:
import functools t = (1, 2, 3) res = functools.reduce(lambda aggregate, element: aggregate * element, t) print(res) # 6
Here’s a basic example using the addition aggregation:
import functools t = (1, 2, 3) res = functools.reduce(lambda aggregate, element: aggregate + element, t) print(res) # 6
Here’s a basic example using the subtraction aggregation:
import functools t = (1, 2, 3) res = functools.reduce(lambda aggregate, element: aggregate - element, t) print(res) # -4
In case you need some repetition or additional information on the reduce() function, run this video:
💡 Info: The
reduce() function from Python’s
functools module aggregates an iterable to a single element. It repeatedly merges two iterable elements into a single one as defined in the function argument. By repeating this, only a single element will remain — the return value.
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.