Thursday, May 31, 2018

(i)t(er)able for one

When you expect that a sequence will only have one item, and are only interested in the first it is common to grab the zeroth element.  This will fail if the sequence is unexpectedly empty, but you might unintentionally silently throw away extra elements:

>>> a = 'a'[0]
>>> a = ''[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> a = 'ab'[0]  # oops, silently dropped b


An alternative idiom is to use sequence unpacking with a single item.  This way neither unexpected condition will silently pass.
 
>>> a, = 'a'
>>> a, = ''
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack
>>> a, = 'ab'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

No comments:

Post a Comment