Are all items in list the same?

Chris Angelico rosuav at gmail.com
Mon Jan 7 21:05:09 EST 2019


On Tue, Jan 8, 2019 at 1:03 PM Skip Montanaro <skip.montanaro at gmail.com> wrote:
>
> >
> > >      if len(a) == 0 or all(i == a[0] for i in a[1:]):
> > >
> > You don't need to check the length of the list because if the list is
> > empty, 'all' will return True anyway.
> >
>
> Given the structure of the expression passed as an argument to all(), won't
> you get an IndexError if a is empty without the guard?
>
> (Would try it out if I had an interpreter on my phone...)

No, because the iteration would never happen. If the list is empty,
a[1:] is also empty, and i==a[0] will never be evaluated. So it is
safe. (But I agree that it's not instantly obvious.)

ChrisA



More information about the Python-list mailing list