user3288734
user3288734

Reputation: 71

Compare Values in a List and create Boolean Python

I have a program in which I'm supposed to create a list of 5 numbers and then compare these items to see if they are all the same. I am supposed to compare the numbers of the list and then return a Boolean if it is true or not. (I'm relatively new to programming and am only allowed to use the random Library and the regular library). If anyone could point me in the right direction, I'd really appreciate it.

I've tried things such as

if aList[0] = aList[1] and aList [2] and... aList[4]: 
   Return = True.  

Thanks!

Upvotes: 1

Views: 100

Answers (3)

SingleNegationElimination
SingleNegationElimination

Reputation: 156238

Here's a python3 variation that has short circuit behavior:

ix = iter(aList)
iy = iter(aList)
next(iy)
if all(x == y for x, y in zip(ix, iy)):
    do something

Upvotes: -1

Hugh Bothwell
Hugh Bothwell

Reputation: 56664

return all(aList[0] == aList[i] for i in range(1, len(aList))

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1123240

Use a set():

def all_the_same(lst):
    # all values in aList are the same.
    return len(set(lst)) == 1

This works for any list of hashable values; strings, integers, booleans, tuples with hashable contents, floats (if they are exactly the same), etc.

Upvotes: 5

Related Questions