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

7 comments:

  1. Pretty good post. I have just stumbled upon your blog and enjoyed reading your blog posts very much. I am looking for new posts to get more precious info. Big thanks for the useful info. 안전놀이터

    ReplyDelete
  2. This is an excellent article. I recently discovered your blog and have quite liked reading your writings. I'm looking for the best essay website where I may learn more useful information. Thank you very much for the excellent information.

    ReplyDelete