Search code examples
pythonpython-3.xtypeerrorpython-3.8

How to solve this error from this python code? (((unsupported operand type(s) for -: 'list' and 'int')))


I have some code like:

a=int(input("Add a:"))
b=int(input("Add b:"))
c=int(input("Add c:"))
d=int(input("Add d:"))
r_list=[a,b,c,d]

for i in r_list:
    y= r_list-2
    print (y)

How can I subtract 2 from each element of the list using a function?


Solution

  • The most Pythonistic approach would be using a list comprehension:

    decreased_r_list = [x - 2 for x in r_list]

    You could also extract the transformation into a function (which for this simple example would be an overkill):

    def minus_two(num):
        return num - 2
    
    decreased_r_list = [minus_two(x) for x in r_list]
    

    This will return a new list containing the transformed elements. Generally, flat is better than nested, so the more you use list comprehension and a more functional-programming approach, the better.