Saturday, June 9, 2018

What is List Comprehension in Python?

Python supports list comrpehension. List Comprehension is a cool way to create a list (based on list construct). The examples are run on Python 3.7.

Here is an excerpt from Wikipedia:

"A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions."

You can create a list in Python using a for loop:


ListComprehension_0

Python supports List comprehension and you can create the same list as shown here:


ListComprehension_1

Don't you think this is far easier. It turns out it is more efficient as well since you avoid append().

You can do this kind of operation as well.


ListComprehension_2


You can filter the list in list comprehension also:

ListComprehension_3


No comments: