List Comprehension in Python

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.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store