Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all numbers in a list are same sign in Python?

How can I tell if a list (or iterable) of numbers all have the same sign?

Here's my first (naive) draft:

def all_same_sign(list):

    negative_count = 0

    for x in list:
        if x < 0:
            negative_count += 1

    return negative_count == 0 or negative_count == len(list)

Is there a more pythonic and/or correct way of doing this? First thing that comes to mind is to stop iterating once you have opposite signs.

Update

I like the answers so far although I wonder about performance. I'm not a performance junkie but I think when dealing with lists it's reasonable to consider the performance. For my particular use-case I don't think it will be a big deal but for completeness of this question I think it's good to address it. My understanding is the min and max functions have O(n) performance. The two suggested answers so far have O(2n) performance whereas my above routine adding a short circuit to quit once an opposite sign is detected will have at worst O(n) performance. Thoughts?

like image 957
User Avatar asked Nov 26 '22 22:11

User


1 Answers

You can make use of all function: -

>>> x = [1, 2, 3, 4, 5]

>>> all(item >= 0 for item in x) or all(item < 0 for item in x)
True

Don't know whether it's the most pythonic way.

like image 145
Rohit Jain Avatar answered Nov 29 '22 14:11

Rohit Jain