Unsupported operand type(s) for +: 'int' and 'str'

PythonPython 3.xListInt

Python Problem Overview


I am currently learning Python so I have no idea what is going on.

num1 = int(input("What is your first number? "))
num2 = int(input("What is your second number? "))
num3 = int(input("What is your third number? "))
numlist = [num1, num2, num3]
print(numlist)
print("Now I will remove the 3rd number")
print(numlist.pop(2) + " has been removed")
print("The list now looks like " + str(numlist))

When I run the program, entering in numbers for num1, num2 and num3, it returns this: Traceback (most recent call last):

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

Python Solutions


Solution 1 - Python

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Solution 2 - Python

try,

str_list = " ".join([str(ele) for ele in numlist])

this statement will give you each element of your list in string format

print("The list now looks like [{0}]".format(str_list))

and,

change print(numlist.pop(2)+" has been removed") to

print("{0} has been removed".format(numlist.pop(2)))

as well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3077439View Question on Stackoverflow
Solution 1 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 2 - PythonSiva CnView Answer on Stackoverflow