Similar to using all , you can use any , which has the advantage of better performance, since it breaks the loop at the first occurrence of a different sign:
def all_same_sign(lst): if lst[0] >= 0: return not any(i < 0 for i in lst) else: return not any(i >= 0 for i in lst)
It would be a little difficult if you want to consider 0 as belonging to both groups:
def all_same_sign(lst): first = 0 i = 0 while first == 0: first = lst[i] i += 1 if first > 0: return not any(i < 0 for i in lst) else: return not any(i > 0 for i in lst)
In any case, you repeat the list once, not twice, as in the other answers. Your code has the disadvantage of loop iteration in Python, which is much less efficient than using built-in functions.
source share