Are all items in list the same?

Tim Chase python.list at tim.thechases.com
Mon Jan 7 20:03:07 EST 2019


On 2019-01-07 17:14, 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?

Since python2.5 you've had any() and all() functions that make this
pretty tidy and they bail early if proven to not be the case (so if
you have hundreds of thousands of items in the list and you know by
the 2nd one that they're not equal, you don't have to touch hundreds
of thousands of items; just the first two).  So I'd do something like

  def all_equal(iterable):
    i = iter(iterable)
    first = next(i)
    return all(x == first for x in i)

It's undefined for an empty list (well, it throws a StopIteration
but you can special-case that), but should hand the cases with
1 element and 2+ elements (both matching and where any item is not
the same). It should work on an iterator as well but will consume the
items in the process.

And I even like how nicely it reads :-)

-tkc







More information about the Python-list mailing list