Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Anthony Cantin
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.
Here is an example of how the error occurs.
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.
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.
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.
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.
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.
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:
Name | Description |
---|---|
iterable | the iterable whose items to sum |
start | sums 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.
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.
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.