List Comprehension in Python

Abinash Panda
1 min readNov 30, 2020

Every now and then we come across List and Dict operations in our code. Python gives great syntactical sugar to work with List and Dicts.

Photo by Clément H on Unsplash

Whether it is initializing a new list or transforming an existing list, list comprehension is often very handy.

Consider the following code:

Now we want to capitalize the fruit names. Instead of writing multi liner for loops like this

We can achieve the same thing in a single liner with Python’s list comprehension:

This is awesome. The syntax to remember is:

output = [expression for item in collection]
or
output = [doSomething() for var in list]

Let’s look at a few more examples:

Performance Comparison:

Python List comprehension is generally much faster than normal for loops. Here is a comparison of the same:

For loop vs List Comprehension

Conclusion:

List Comprehension is a powerful and beautiful tool available in Python for developers, also comes with great efficiency.

--

--

Abinash Panda

ML Engineer | Full Stack Developer | Technology Enthusiast | Sports Lover