'I make a function, return True if all value of list is equal, otherwise False [closed]
My Task is to create a function that returns True if all values in the list are the same.
Example IN/OUT:
l = [1,1,1,1,1] # True
l = [2,2,2,2,2,5] # False
But this function not check all values.
def all_equal(list_):
equal = list_[0]
for a in list_:
if a == equal:
return True
else:
return False
break
print(all_equal([1, 2, 1, 1]))
Solution 1:[1]
I understood you want to check if all values within a list are equal.
You get True
because you use return
so the loop stops after the first iteration.
def all_equal(list_):
equal = list_[0]
for a in list_:
if a != equal:
return False
return True
(EDIT: the first approach with a variable has been removed, it's still in the post history)
Solution 2:[2]
You could use a set
to remove duplicate elements from the list.
>>> l = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> set(l)
{1, 2, 3, 4, 5}
>>> l = [2, 2, 2, 2, 2, 2, 2]
>>> set(l)
{2}
If a list contains only one kind of element, then the set will contain only one element. This means that you can write the function like this:
def all_equal(list_):
return len(set(l)) == 1
Or simply:
all_equal = lambda l: len(set(l)) == 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sharim Iqbal |
Solution 2 |