Daniel Larson
Daniel Larson

Reputation: 81

Checking elements in a list of integers for positive or negative values

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")

Upvotes: 0

Views: 2929

Answers (2)

hpchavaz
hpchavaz

Reputation: 1388

Solution

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

Explanation

The onliner code use list comprehension to create the list.

  1. ('negative', 'zero', 'positive') is the strings tuple from which the string will be fetched.

  2. [((n > 0) - (n < 0)) + 1] fetch the string. Lets decompose this one:

    The subexpression (se) (n > 0) - (n < 0) gives the sign of n (-1 if n < 0, 0 if n == 0, +1 if n > 0) Note : Python does not have a sign function.

    # Keep in mind that True = 1 and False = 0
    if n < 0  'se' evaluates to False - True  => 0 - 1 => -1
    if n > 0  'se' evaluates to True  - False => 1 - 0 =>  1
    if n == 0 'se' evaluates to False - False => 0 - 0 =>  0
    
  3. Then we add 1 to get : 0 if n < 0, 1 if n = 0, 2 if n > 0.

  4. Lastly, we use this integer as an index in the strings tuple.

The equivalent code is:

strings=('negative', 'zero', 'positive')

def sign(n):
    """Returns the sign of n: -1 if n < 0, 0 if n == 0, +1 if n > 0"""
    return (n > 0) - (n < 0)
    
rtn = [] # will get the result
for n in lst:
    index = sign(n) + 1
    string = strings[index]
    rtn.append(string)

Upvotes: 1

Vincent B&#233;net
Vincent B&#233;net

Reputation: 1314

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'] 

Upvotes: 0

Related Questions