Surprises

In a way, tuples are one of the most magical parts of Python. How does the interpreter distinguish between a method call, a bracketed portion of a mathematical expression and an actual tuple?:

calc_midpoint (1, None, [2, 3], False)
x = w + (x * y)
a = (b, c)

The really smart thing is that Python rarely mistakes the meaning you intend, otherwise "accidental" tuples would make writing code painful. But when it does, the symptoms can be baffling.

Writing a multi-element tuple is easy: (a, b, c). When you first come to writing a single element tuple however, it can be baffling:

a = (2) # this is the integer 2
b = ((2)) # this is still the integer 2
c = tuple (2) # this fails as 2 is not iterable

The answer is delightfully simple, and relies on Python's tolerance of excessive commas (something I wish Javascript had):

d = (2,)  # this is a tuple
d = 2,    # as is this

However, stray commas can cause problems. It took me nearly an hour to spot why this list was being mis-interpreted as a tuple containing the list:

e = [ 1, 2, 3, ],

Hint: it's the trailing comma.