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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

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

int argument must be string or real number not nonetype

Here is an example of how the error occurs.

main.py
my_list = ['3', '5', '8'] # ⛔️ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list' result = int(my_list)

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

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

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

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

main.py
my_list = ['3', '5', '8'] my_str = ''.join(my_list) print(my_str) # 👉️ '358' my_int = int(my_str) print(my_int) # 👉️ 358

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 list contains numbers, or other types, convert all of the values to string before calling join().

main.py
my_list = ['3', 5, 8] my_str = ''.join(map(str, my_list)) print(my_str) # 👉️ '358' my_int = int(my_str) print(my_int) # 👉️ 358

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 list to integers.

main.py
my_list = ['3', '5', '8'] new_list = [int(x) for x in my_list] print(new_list) # 👉️ [3, 5, 8]

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

Conclusion #

The Python "TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list'" occurs when we pass a list to the int() class. To solve the error, access a specific item in the list and pass the item to the int() class, e.g. int(my_list[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.