int() argument must be a string or real number not 'tuple'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

int() argument must be a string or real number not 'tuple' #

The Python "TypeError: int() argument must be a string, a bytes-like object or a real number, not 'tuple'" occurs when we pass a tuple to the int() class. To solve the error, access a specific item in the tuple and pass the item to the int() class, e.g. int(my_tuple[0]).

int argument must be string or real number not tuple

Here is an example of how the error occurs.

main.py
my_tuple = ('1', '2', '3') # ⛔️ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'tuple' result = int(my_tuple)

We passed an entire tuple to the int() class which caused the error.

One way to solve the error is to access the tuple at a specific index and pass the item to the int() method.

main.py
my_tuple = ('1', '2', '3') result = int(my_tuple[0]) print(result) # 👉️ 1
Indices are 0 based, so the first item in the tuple has an index of 0, and the last - an index of -1.

If you meant to join all the items in the tuple into a string and convert the result to an integer, use the join() method.

main.py
my_tuple = ('1', '2', '3') my_str = ''.join(my_tuple) print(my_str) # 👉️ '123' my_int = int(my_str) print(my_int) # 👉️ 123

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your tuple contains numbers, or other types, convert all of the values to string before calling join().

main.py
my_tuple = ('1', '2', '3') my_str = ''.join(map(str, my_tuple)) print(my_str) # 👉️ '123' my_int = int(my_str) print(my_int) # 👉️ 123

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

You can also use a list comprehension if you need to convert all items in a tuple to integers.

main.py
my_tuple = ('1', '2', '3') new_tuple = tuple([int(x) for x in my_tuple]) print(new_tuple) # 👉️ (1, 2, 3)

We pass each string in the tuple to the int() class to convert each item to an integer.

You can use the tuple() class to convert the list back to a tuple.

Conclusion #

The Python "TypeError: int() argument must be a string, a bytes-like object or a real number, not 'tuple'" occurs when we pass a tuple to the int() class. To solve the error, access a specific item in the tuple and pass the item to the int() class, e.g. int(my_tuple[0]).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.