List comprehensions

Jayashree domala
2 min readOct 5, 2020

--

A guide to understanding the list comprehensions in Python

List comprehensions are a unique way of quickly creating a list in Python.

>>> str1 = 'python'
>>> list1 = []
>>> for i in str1:
list1.append(i)
>>> list1
['p', 'y', 't', 'h', 'o', 'n']

There is a more efficient way to do the same thing.

>>> list1 = [i for i in str1]
>>> list1
['p', 'y', 't', 'h', 'o', 'n']
>>> list2 = [pizza for pizza in 'amazing']
>>> list2
['a', 'm', 'a', 'z', 'i', 'n', 'g']
>>> list3 = [x for x in range(0,5)]
>>> list3
[0, 1, 2, 3, 4]

Now if we have to do operations on x and get the square of each number.

>>> list4 = [x**2 for x in range(0,5)]
>>> list4
[0, 1, 4, 9, 16]

Now we add ‘if’ conditional statements and get only even numbers.

>>> list5 = [x for x in range(0,5) if x%2==0]
>>> list5
[0, 2, 4]
>>> quantity = [1,2,3,4]
>>> cost = [(quant*5) for quant in quantity]
>>> cost
[5, 10, 15, 20]

Adding ‘if’ and ‘else’ statements.

>>> numbers = [num if num%2==0 else 'Odd' for num in range(0,10)]
>>> numbers
[0, 'Odd', 2, 'Odd', 4, 'Odd', 6, 'Odd', 8, 'Odd']

Implementing nested loops.

>>> l = []
>>> for x in [1,2,3]:
for y in [11,22,33]:
l.append(x*y)
>>> l
[11, 22, 33, 22, 44, 66, 33, 66, 99]

Doing it the more efficient way is as follows.

>>> l1 = [x*y for x in [1,2,3] for y in [11,22,33]]
>>> l1
[11, 22, 33, 22, 44, 66, 33, 66, 99]

Refer to the notebook here.

Beginner-level books to refer to learn Python:

Advance-level books to refer to learn Python:

Reach out to me: LinkedIn

Check out my other work: GitHub

--

--

Jayashree domala
Jayashree domala

Written by Jayashree domala

Self-driven woman who wishes to deliver creative and engaging ideas and solutions in the field of technology.

No responses yet