Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Sunny Ng
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])
.
Here is an example of how the error occurs.
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.
my_list = ['3', '5', '8'] result = int(my_list[0]) print(result) # 👉️ 3
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.
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()
.
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 on each item of the iterable.
You can also use a list comprehension if you need to convert all items in a list to integers.
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.