Python

# List Comprehensions in Python

Another beautiful concept in the Python language is list comprehensions. It is an very powerful but easy way of creating a list. Let us learn though an anology in mathematics.

We all have studied sets in Mathematics and hence the following sentence makes sense to us:

S = {x^2: x in {0,1,...6}}

i.e. S = {0, 1, 4, 9, 16, 25, 36}

Python language emulates this way of creating a list and

S = {x^2: x in {0,1,...6}} is represented in Python as:

S = [x**2 for x in range(0,7)]

The list comprehensions works on all data types.For example if you want to find all the words with length 4 from a string.

str = "I love to code in my free time"
words = str.split()
wordsArray = [w for w in words if len(w) == 4]

After running this code, wordsArray becomes ['love','code','free','time']

List Comprehensions is a very helpful tool and I am sure you guys will putit in great use.



By Gaurav Israni

@gaurav.israni


Learn More


  • List Comprehensions in Python