1

I have an array with a random elements. How can I check, is all that elements the same or not? Could it be possible with numpy.all ? Thanks

Gajanan Kulkarni
  • 697
  • 6
  • 22
Tina Ch
  • 39
  • 1
  • 6
  • 1
    `len(set(my_array))==1` ? – PRMoureu Oct 21 '17 at 14:08
  • Convert it to a set and check it is of size 1. Bah just beaten to it – Nick is tired Oct 21 '17 at 14:08
  • 1
    I am not agree with marking this post as duplicated because it is related to ```numpy.array``` and not to the ```list```. And, yes, you could check identity with ```numpy.all(your_array == your_array[0])``` – Timofey Chernousov Oct 21 '17 at 14:12
  • 2
    Another one: `numpy.unique(a).size == 1` – Daniel Oct 21 '17 at 14:19
  • @TimofeyChernousov Unfortunately, it is such a basic question that I can't find a duplicate for it. I didn't read the question to the end, only the title and tags. – cs95 Oct 21 '17 at 14:21
  • 1
    @TimofeyChernousov: However, the first link I found without fail was the link to the np.all docs, which explicitly document this behaviour. If OP is not willing to put in that much effort to do a little research, this question doesn't deserve to be reopened. – cs95 Oct 21 '17 at 14:22

1 Answers1

2

You can use all:

if all(i == a[0] for i in a):   
   #all the elements are the same
   pass

You can also use a set:

if len(set(a)) == 1:
   #all the elements are the same
   pass
Ajax1234
  • 69,937
  • 8
  • 61
  • 102