Python List Comprehensions

tags #cs

Syntax

A concise way to create lists based on existing iterables.

[expression for item in iterable if condition]

Examples

Squaring numbers:

numbers = [1, 2, 3]
squared = [x ** 2 for x in numbers] # [1, 4, 9]

Dictionary Comprehension:

{x: 3*x for x in numbers} # {1: 3, 2: 6, 3: 9}

Set Comprehension:

{x / (x + 1) for x in numbers}