Best way to check that you are at the beginning (the end) of an iterable?

Peter Otten __peter__ at web.de
Fri Sep 9 13:04:57 CEST 2011


Cameron Simpson wrote:

> About the only time I do this is my personal "the()" convenience
> function:
> 
>   def the(list, context=None):
>     ''' Returns the first element of an iterable, but requires there to be
>         exactly one.
>     '''
>     icontext="expected exactly one value"
>     if context is not None:
>       icontext=icontext+" for "+context
> 
>     first=True
>     for elem in list:
>       if first:
>         it=elem
>         first=False
>       else:
>         raise IndexError, "%s: got more than one element (%s, %s, ...)" \
>                           % (icontext, it, elem)
> 
>     if first:
>       raise IndexError, "%s: got no elements" % icontext
>       
>     return it
> 
> Which I use as a definite article in places where an iterable should
> yield exactly one result (eg SQL SELECTs that ought to get exactly
> one hit). I can see I wrote that a long time ago - it could do with some
> style fixes. And a code scan shows it sees little use:-)

A lightweight alternative to that is unpacking:

>>> [x] = ""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack
>>> [x] = "a"
>>> [x] = "ab"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack




More information about the Python-list mailing list