Python List Comprehension

Mike Sun
1 min readJul 14, 2020

--

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.

basic for-loop
list comprehension

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Mike Sun
Mike Sun

Written by Mike Sun

Random tech blog for my fellow peers troubleshooting stuff. Things I wished I knew without needing to spend hours/days digging...

No responses yet

Write a response