Skip to main content
Python List Comprehension

Python List Comprehension

In this post, we will cover list comprehensions in python with examples. List comprehension is the process of making lists out of existing iterables.

List comprehension can also be regarded as a simpler and more appealing way of representing for and if loops. Loop comprehensions are slower than list comprehensions.

Python List Comprehension Example

We can demonstrate some examples using python list comprehension:

The simple Syntax:

[expression for element in iterable if condition]

For Loop Comprehension

We ll take an example of for loop then develop the same process using comprehension.

We’ll convert to 5 number square:

squares = []
for n in range(5):
   squares.append(n * n)
   print(squares)

Output:
[0, 1, 4, 9, 16]

in the above code, We’ve created an empty list called squares. Then, to iterate across the range, we use a for loop (5). Finally, we add the result to the end of the list by multiplying each integer by itself.

We can create the same functionality using list comprehension in only one line of code:

squares = [i * i for i in range(5)]

Output:
[0, 1, 4, 9, 16]

You define the list and its contents at the same time, rather than starting with an empty list and adding each element at the end.

Multiple If condition with comprehension

we can also implement list comprehension with multiple lists:

nums = [x for x in range(10) if x > 0 if x%5==0]
print(nums)

Output:
[0, 10]

You can also checkout other python tutorials:

String Comprehension

We ll make string comprehension as like below:

employees = ['Ajay', 'Rukh', 'Rajesh', 'Viji']
names2 = [s for s in employees if 'a' in s]
print(names2)

Output:
['Ajay', 'Rajesh']

in the above code, We’ve created an employee list. I have iterated on a string list and checked ‘a’ character exists into the item list.

One thought to “Python List Comprehension”

Leave a Reply

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