Home > Software design >  Checking elements in a list of integers for positive or negative values
Checking elements in a list of integers for positive or negative values

Time:10-18

I have a predetermined created list of integers that I want to traverse and append "positive" or "negative" if the value meets the criteria. However it is throwing "TypeError: '>' not supported between instances of 'str' and 'int' on the first line of my if statement. I have seen this error before when getting user input and must convert the input to a int, but my list is already an integer, so I am confused on what I need to fix. It is throwing the error on if lst[i] > 0:

lst = [-2, 1, -2, 7, -8, -5, 0, 5, 10, -6, 7]

for i in lst:
    if lst[i] > 0:
        lst.append("positive")
    elif lst[i] < 0:
        lst.append("negative")
    else:
        lst.append("zero")

CodePudding user response:

You should do like this:

lst = ["positive" if el > 0 else "negative" if el < 0 else "zero" for el in [-2, 1, -2, 7, -8, -5, 0, 5, 10, -6, 7]]

Much faster and clean way to create what you need.

return:

['negative', 'positive', 'negative', 'positive', 'negative', 'negative', 'zero', 'positive', 'positive', 'negative', 'positive'] 

CodePudding user response:

[('negative', 'zero', 'positive')[((n > 0) - (n < 0)) 1] for n in lst]
  • Related