In my personal opinion, Python’s comprehension syntax is one of the features that makes Python truly Pythonic. Among the many Python features, it best represents the philosophy and expressiveness of the language. (This is purely my personal opinion, so feel free to disagree.)
Let’s dig into what comprehension is first. I believe comprehension is what makes Python code shorter and more efficient. While I’m not entirely sure if it always makes code easier to read or understand, it definitely allows us to write simpler and faster code.
I’ve heard that there are (at least) two types of developers, those who believe that code should be easy to read, and those who believe that code should be efficient even if it becomes a bit harder to read.
However, regardless of what type of developer you are, it’s undeniable that comprehension saves time once you’re familiar with it.
How to use
Let’s say we need to write code to calculate squares. We’ll look at two versions! one without using comprehension and one using comprehension.
This code is with using without comprehension, and if you have learnt basic python, i am pretty sure you can understand what this code does. I personally think this code may be simple comparing to the other programming languages such as Java, C but still i don’t want to say this code is Pythonic.
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(number * number)
print(squares)
Python
복사
This code is without using comprehension, and it looks way simpler than not using it.
numbers = [1, 2, 3, 4, 5]
squares = [number * number for number in numbers]
print(squares)
Python
복사
Let’s break into how the comprehension works!



