TypeError: unsupported operand type(s) for +: int and list

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

TypeError: unsupported operand type(s) for +: int and list #

The Python "TypeError: unsupported operand type(s) for +: 'int' and 'list'" occurs when we try to use the addition (+) operator with a number and a list. To solve the error, figure out where the variable got assigned a list and correct the assignment, or access a specific value in the list.

typeerror unsupported operand type for plus int and list

Here is an example of how the error occurs.

main.py
my_int = 10 my_list = [20, 30, 40] # ⛔️ TypeError: unsupported operand type(s) for +: 'int' and 'list' result = my_int + my_list

We are trying to use the addition (+) operator with a list and a number.

To solve the error, you have to figure out how the variable got assigned a list object and correct the assignment.

If you need to iterate over the list and add a value to each number, use a list comprehension.

main.py
my_int = 10 my_list = [20, 30, 40] my_new_list = [x + my_int for x in my_list] print(my_new_list) # 👉️ [30, 40, 50]

The same can be achieved using a simple for loop.

main.py
my_int = 10 my_list = [20, 30, 40] my_new_list = [] for num in my_list: my_new_list.append(num + my_int) print(my_new_list) # 👉️ [30, 40, 50]

If you need to use the addition (+) operator on an item in the list, access the item at its specific index.

main.py
my_int = 10 my_list = [20, 30, 40] result = my_int + my_list[0] print(result) # 👉️ 30

We accessed the list item at index 0 and added 10 to it.

If you need to get the sum of the list, use the sum() function.

main.py
my_int = 10 my_list = [20, 30, 40] result = my_int + sum(my_list) print(result) # 👉️ 100 print(sum(my_list)) # 👉️ 90

The sum function takes an iterable, sums its items from left to right and returns the total.

The sum function takes the following 2 arguments:

NameDescription
iterablethe iterable whose items to sum
startsums the start value and the items of the iterable. sum defaults to 0 (optional)

You can pass the other number as the start value to the sum() function.

main.py
my_int = 10 my_list = [20, 30, 40] result = sum(my_list, my_int) print(result) # 👉️ 100 print(sum(my_list)) # 👉️ 90

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_int = 10 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True my_list = [20, 30, 40] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Use the search field on my Home Page to filter through my more than 1,000 articles.