Single-element tuples

Sometimes a single element tuple is required. To write this, we can't just use a simple object in parentheses. This is because Python parses that as an object enclosed in the precedence controlling parentheses of a math expression:

>>> h = (391)
>>> h
391
>>> type(h)
<class 'int'>

To create a single-element tuple we make use of the trailing comma separator which, you'll recall, we're allowed to use when specifying literal tuples, lists, and dictionaries. A single element with a trailing comma is parsed as a single element tuple:

>>> k = (391,)
>>> k
(391,)
>>> type(k)
<class 'tuple'>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset