Are all items in list the same?

ike at koeln.ccc.de ike at koeln.ccc.de
Mon Jan 7 19:47:04 EST 2019


You might do something like

    if len(a) == 0 or all(i == a[0] for i in a[1:]):

This should be linear complexity and short circuiting and in general it
doesn't get much better than this. Though I wouldn't bet there isn't a
better (faster/clearer/more readable) solution.

On Mon, Jan 07, 2019 at 05:14:14PM -0700, Bob van der Poel wrote:
> I need to see if all the items in my list are the same. I was using set()
> for this, but that doesn't work if items are themselves lists. So, assuming
> that a is a list of some things, the best I've been able to come up with it:
> 
>     if a.count( targ ) == len(a):
> 
> I'm somewhat afraid that this won't scale all that well. Am I missing
> something?



More information about the Python-list mailing list