Skip to content

List Comprehension in Python

In this Python Tutorial we will be learning about Lists Comprehension in Python. List comprehension provides a simple and concise way to create lists.


In this Python Tutorial we will be learning about Lists Comprehension in Python. List comprehension provides a simple and concise way to create lists. It is a great feature that every Python programmer should know!

We will learn:

  • What is list comprehension and why should we use it
  • How do we use list comprehension
  • The syntax of list comprehension
  • The extended syntax with conditional statements
  • Set and Dictionary Comprehension
  • Speed Comparison: List comprehension vs. For-Loops

You can find and test the code on GitHub.

Avoid for loops!

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

Better: Use list comprehension

# new_list = [expression for member in iterable]
squares = [i * i for i in range(5)]
print(squares)
An iterable can be a list, set, sequence, generator, or any other iterable.

The expression can be a function:

def cube(i):
    return i*i*i

cubes = [cube(i) for i in range(5)]
print(cubes)

Filtering

# new_list = [expression for member in iterable (if conditional)]
evens = [i for i in range(20) if i%2 == 0]
print(evens)

def is_even(i):
    return i%2 == 0

evens = [i for i in range(20) if is_even(i)] 
print(evens)   

Modifying

# new_list = [expression (if else conditional) for member in iterable]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [10 if i > 5 else 0 for i in a]
print(b)

Set comprehension

quote = "hello everybody"
unique_vowels = {i for i in quote if i in 'aeiou'}
print(unique_vowels)

squares = {i: i * i for i in range(5)}
print(squares)

Nested list comprehension

Use sparely! This can be more confusing most if the times.

matrix2d = [[i*j for i in range(5)] for j in range(1,3)]
print(matrix2d)

List comprehension vs generator

A list comprehension in Python works by loading the entire output list into memory -> use genereator for large data!
Generators can also be created with generator expressions:

# new_generator = (expression for i in iterable)

s = sum([i * i for i in range(1000)])
print(s)

s = sum((i * i for i in range(1000)))
print(s)

import sys
l = [i * i for i in range(1000)]
print(sys.getsizeof(l), "bytes")
g = (i * i for i in range(1000))
print(sys.getsizeof(g), "bytes")

A word about speed:

Somtetimes it can be faster, but this may not always be the case!

from timeit import default_timer as timer
start = timer()
a = [i*i for i in range(1_000_000)]
stop = timer()
print(f'{stop-start:.4f} seconds')

start = timer()
a = []
for i in range(1_000_000):
    a.append(i*i)
stop = timer()
print(f'{stop-start:.4f} seconds')


FREE VS Code / PyCharm Extensions I Use

鉁 Write cleaner code with Sourcery, instant refactoring suggestions: Link*


PySaaS: The Pure Python SaaS Starter Kit

馃殌 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 馃檹