2

I have an array, say [4 4 4 4 4], here the length is 5. In real case it could be 300. How to check whether all the elements are same, say in this case all are 4. If all elements have same value, the function return true, otherwise false. The element could be only interger and value could be either one of them: 0,1,2,3,4.

I could use a loop in Python as follows. But I am looking for a concise way or simple way to do that, say one line.

x= [4,4,4,4]
temp = x[0]

for ele in x:
    if(temp != ele):
        false
     true
1
  • 1
    len(set(array)) == 1 Commented Jun 19, 2020 at 8:48

2 Answers 2

6

it might be more efficient not to iterate over the full list (as does the set constructor) but to stop at the first element that does not equal x0. all does that for you:

x = [4,4,4,4]
x0 = x[0]

print(all(item == x0 for item in x))
# True

this is basically the same version you had; only the loop will be much more efficient this way.

also note that true and false are not valid python identifiers. in python it is True and False.

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

Comments

4

You can put elements into set() and then check if length of the set is equal to 1:

if len(set(x)) == 1:
    print('All elements are same')
else:
    print('Not same')

Comments

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.