0

How do I check if every value in a list is equal to another value, x? For example, if I had a list that was completely full of the number 100, how would I return false based on that condition. Or if a list was full of the number 100 except for one single element which was 88, then I'd want to return true and for the if statement to execute.

Thank you.

Elliot Killick
  • 389
  • 2
  • 4
  • 12
  • `l.count(x) != len(l)`? – miradulo Jul 30 '17 at 17:21
  • 2
    You could also create a set from the list. If it has one element and that element has value 100 then your original list was all 100s. – jarmod Jul 30 '17 at 17:22
  • @jarmod This solution is a bit restrictive, though. Now you can only handle hashable types, and building a set probably a bit more costly. – miradulo Jul 30 '17 at 17:24
  • just return from a function ... `False if len(set(input_list)) == 1 else True` and take `input_list` as argument. – Hara Jul 30 '17 at 17:36

2 Answers2

1

Python has an builtin any() function, e.g.:

In []:
lst = [100]*5
x = 100
print(lst)
any(a != x for a in lst)

Out[]:
[100, 100, 100, 100, 100]
False

In []:
lst[2] = 88
print(lst)
any(a != x for a in lst)

Out[]:
[100, 100, 88, 100, 100]
True
AChampion
  • 29,683
  • 4
  • 59
  • 75
0

you could use python set to do this , By definition a set is a well-defined collection of distinct objects,

if len(set(input_list))! =1: print "not all items in the set are the same"