Become a Better Pythonista by Abusing List Comprehensions and :=

Friday, May 26

15:25 - 15:55
Audience levelIntermediate
Elevator pitch

The goal? Being able to replace any loop with comprehensions. Why? By talking non-stop about all the features of comprehension and the walrus operator, I’ll (easily!) convince you that, by mastering some Python aspects to the extent of abusing them, you’ll improve in your daily coding.


The structure of the talk will be based on taking increasingly large snippets of normal-looking code and translating them into not-so-normal comprehension monsters.

And I promise you it’s a good idea. As an example, that’ll give us the chance to cover:

  • How to use multiple loops in one comprehensions!

E.g.: do you know the difference between [[x+y for y in range(10)] for x in range(10)] and [x+y for y in range(10) for x in range(10)]?

  • How to use generator comprehension!

E.g.: do you know what happens if you remove the [] from sum([x for x in range(10)])? Does it still work?

  • How to know what happens when you use the walrus operator, featuring examples that stumped even expert pythonistas!

E.g.: are the following lines correct? If not, how could you fix them?

function(function := print)

assert ((value := 5) if value else 3) == 5

print(*[value := x for x in range(5)], sep=str(value))

  • How to use the dict comprehension!

E.g.: would you be able to re-implement all built-in dictionary operations as one-liners?

  • Review of how or and and can be used in expressions and why they can confuse you or make the code clear!

E.g.: what’s the value of a after executing the following line?

((a := 5) and (a := 0) or (a := a + 1)) and ((a := a + 1) and (a - 2) and (a := 5))

And so on. Yes, all of these are examples constructed to be intentionally obscure; but being able to see through them will be very useful as soon as you’ll meet some unintentionally obscure legacy code.

TagsClean Code
participant photo

Niccolò Venerandi

I study Mathematics in Genoa and Stockholm. I do promotion and development for the open-source organization KDE. I have a Youtube channel regarding Linux desktops and their designs. I’ve taught Python to elementary and middle school students; I’ve also once taught it at CNR.