Python has a great documentation section called “what’s new in Python” that discusses new features added in each version of Python. I recently read through all of them and learned several new tricks! From now on, I’ll be sure to read these each time a new version of Python is released.
One fun lesson: “01” is not a valid number in Python.
>>> (00, 01, 10, 11) File "<stdin>", line 1 (00, 01, 10, 11) ^ SyntaxError: invalid token
Why? Python previously treated numbers starting with 0 as octal. As of Python 3,
such numbers must now be prefixed with
0o, as in
0o31. In order to avoid
subtle bugs, integers other than 0 are no longer allowed to start with 0 or -0.
Unpacking support has been improved multiple times over the past several releases. The following now works nicely.
>>> (a, *rest, b) = range(5) >>> a 0 >>> rest [1, 2, 3] >>> b 4
>>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined >>> exec("x = 5") >>> x 5
eval function, known primarily for horrifying security-minded
programmers the world over, has a Python equivalent! “This function supports
dynamic execution of Python code.” Read more in the docs, then forget that
Taking a slice of a generator, like range, can return another generator. Cool!
>>> range(0, 100, 2)[0:5] range(0, 10, 2)
yield from expressions allow deferring to other generators within a generator.
>>> def g(x): ... yield from range(x, 0, -1) ... yield from range(x) ... >>> list(g(5)) [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
The list of Python modules is also remarkably short and worth skimming. Modules that I was at most vaguely aware of, and inspired by the list to investigate more, include: