1

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!

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-1

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

2 Comments

Not allowed to use outside libraries other than random
Note, in python 2, zip is eager (returns a list) instead of lazy; you can get the iterator version of zip as itertools.izip in the python standard library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.