Tags

A while ego, Python veteran Raymond Hettinger published a following tweet –

Capture

Being a novice in Python, I couldn’t make much of it, so I ran it for Python 2.7 (yes, I am still onto Python 2.7). The output was 4. Somehow it didn’t make sense to me. I again ran it on Python 3 and this time, output was 10. Later on, I came to know that this was essentially a bug rather than a feature in Python 2.x as list comprehensions were known to leak their variables (see this Stack Overflow discussion). However, the same has been fixed for Python 3. That had been some experience.

All this while, I had also been casually browsing through Fluent Python book by Luciano Ramalho and I found this book to be really captivating and I highly recommend this. Writing style is just awesome and what I particularly like about this book is that it leads us to plenty of other external resources.

Soon after my first encounter with ‘leaky list comprehensions’ as mentioned above, I encountered them again in Fluent Python. To my surprise, Ramalho had already addressed the question Hettinger was trying to ask in his tweet.  Had I read this chapter earlier, I wouldn’t have been that much excited about Hettinger’s tweet.

In that very chapter (chapter two), I learned few more interesting things. For example, guess the output of following program: –

t = (1,2, [30,40])
t[2] += [50,60]

Pay attention to += before guessing the output. It doesn’t matter if you are guessing the output for Python2 or Python3. Would it return TypeError? Would ‘t’ become (1,2,[30,40,50,60])? I guessed it would raise TypeError because, well, tuples are immutable. When I ran it for Python2, I was shocked to see the results. This code not only threw the TypeError but it also modified the tuple ‘t’.

Again from the same chapter, I learned few more interesting things. For example, see this code –

t = [('a', 1),('b', 1)]
for i in t:
.... print '%s/%s' %i # 4 dots indicate indentation
#output will be
a/1
b/1

This was pretty small but very interesting example of tuple unpacking and how tuple can be used for records. Also notice how ‘_’ has been used in following examples: –

t = [('a', 1),('b', 1)]
for letter, _ in t:
.... print letter # 4 dots indicate indentation
#output will be
a
b

All these examples are from only one chapter. Usually my reading habit is rather untidy. Few random pages from this book and then few random pages from that book. But still, I think I am actually going to finish this book because I think books like these make Python even more captivating.

Advertisements