There may be occasions when a list will contain all the values which are same. In this article we will see various way to verify that.
With all
We use the all function to find the result of comparison of each element of the list with the first element. If each comparison gives a result of equality then the result is given as all elements are equal else all elements are not equal.
Example
listA = ['Sun', 'Sun', 'Mon'] resA = all(x == listA[0] for x in listA) if resA: print("in ListA all elements are same") else: print("In listA all elements are not same") listB = ['Sun', 'Sun', 'Sun'] resB = all(x == listA[0] for x in listB) if resB: print("In listB all elements are same") else: print("In listB all elements are not same")
Output
Running the above code gives us the following result −
In listA all elements are not same In listB all elements are same
With count
In this approach we count the number of occurrences of the first element and compare it with length of the elements in the list. If all elements are same then this length will match else it will not.
Example
listA = ['Sun', 'Sun', 'Mon'] resA = listA.count(listA[0]) == len(listA) if resA: print("in ListA all elements are same") else: print("In listA all elements are not same") listB = ['Sun', 'Sun', 'Sun'] resB = listB.count(listB[0]) == len(listB) if resB: print("In listB all elements are same") else: print("In listB all elements are not same")
Output
Running the above code gives us the following result −
In listA all elements are not same In listB all elements are same