7.8. Don’t Forget the Comma in Single-Item Tuples¶
When writing tuple values in your code, keep in mind that you’ll still need a trailing comma even if the tuple only contains a single item. Although the value (42, ) is a tuple that contains the integer 42 , the value (42) is simply the integer 42 . The parentheses in (42) are similar to those used in the expression (20 + 1) * 2 , which evaluates to the integer value 42 . Forgetting the comma can lead to this:
>>> spam = ('cat', 'dog', 'moose')
>>> spam[0]
'cat'
>>> spam = ('cat')
>>> spam[0]
'c'
>>> spam = ('cat', )
>>> spam[0]
'cat'
Without a comma, (‘cat’) evaluates to the string value, which is why spam[0] evaluates to the first character of the string, ‘c’ 1. The trailing comma is required for the parentheses to be recognized as a tuple value 2. In Python, the commas make a tuple more than the parentheses.