List comprehension is a really weird thing when I first saw it, but after a while it get’s trivial. Today, we will be exploring this syntax.
Basic for-loop:
lst = []
for i in arr:
lst.append(i)
list comprehension:
a = [i for i in arr]
essentially, the syntax for list comprehension is “expression” for “item” in “list”. And the output will be a list as well.
Another non-trivial code comparison.
So why use list comprehension?
Apart from shorter code, it is supposedly a tad faster than the traditional loop. However actual performance depends on your logic expression. In the end, I still prefer the basic for-loop because it is much more readable for someone coming from another language.