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.
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]
output = [doSomething() for var in list]
Let’s look at a few more examples:
Python List comprehension is generally much faster than normal for loops. Here is a comparison of the same:
List Comprehension is a powerful and beautiful tool available in Python for developers, also comes with great efficiency.