0

I am comparing fist element of list vs all the elements of list. If False is there I need to return false or if all are true, I need to return True. Currently I am doing this with if-else. is there any pythonic way to return bool value

def checker(inp):
    _compare = [ _==inp[0] for _ in inp] 
    return False if False in _compare else True

lst = [5, 5, 5]
lst2 = [5, 5, 6]

# Case 1
level = checker(inp=lst)
print(level)
True

# Case 2 
level2 = checker(inp=lst2)
print(level2)
False

Any pythonic way to achieve this

return False if False in _compare else True
Tarun K
  • 469
  • 9
  • 20

3 Answers3

2

False in _compare is already a boolean so

return False not in _compare

is the best way to do it.

but looking wider:

_==inp[0] for _ in inp

should be

return all(x==inp[0] for x in inp)

so it returns False if one value is False

This solution works even if the items aren't hashable.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

if all the numbers in list are same I want to return True if not False

The most straight forward way:

return len(set(inp)) == 1

This does require the values to be hashable, but simple numbers are.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

Your problem is identical to the question "I need to check if all elements in my list are identical", since both are true for exactly the same cases. So you could also solve it like this:

def checker(inp):
    return len(set(inp)) == 1

If that is the most pythonic way to go about it .. I don't know.

edit: alternative in case of unhashable items:

def checker(inp):
    return not [True for i in range(len(inp) - 1)) if [inp[i] != inp[i+1]]
Arne
  • 17,706
  • 5
  • 83
  • 99