List Comprehension in Python

List comprehension in python is one of the best features present in python.

List Comprehension in python
List Comprehension in python

As we all know, a lot of work done in a lot fewer lines of code in python. This usually speeds up development.

List comprehensions provide a concise way to create lists using for clause, then zero or more for or if clauses depending on your needs. Let’s call this whole thing a “statement”.

We enclose the whole statement inside square brackets. The final result of this is a list.

Let’s look at some examples below.

Example 1 – Squares of first 10 numbers

Here we will try to create a list with squares of first 10 numbers. This will be done both using for loop and list comprehension.

Using for loop

>>> squaresList = []
>>> for i in range (1,11):
...     squaresList.append(i*i)
...
>>> squaresList
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>

Using list comprehension

>>> squaresList = [ (i**2) for i in range (1,11) ]
>>> squaresList
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>

We were able to do the same job in a single line of code using a list comprehension compared to 3 lines in case of a for loop. This may prove more helpful with complex use cases.

Have a doubt on list comprehension in python? Comment below and we will help you out.


Want to learn more about basic lists operations? Click here!

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: