List Comprehension

List comprehension provides a concise way of creating lists.

List Comprehension
(values) = [(expression) for (value) in (collection)]

For Loop
(values) = [] for (value) in (collection): (values).append((expression))

List Comprehension
(values) = [(expression) for (value) in (collection) if (condition)]

For Loop
(values) = [] for (value) in (collection): if (condition): (values).append((expression))

Basic Example
Here is a piece of code that calculates the squares of 0 - 9 NOT using list comprehension. squares = [] for x in range(10): squares.append(x * x) Returns : [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Now here is the same code but using list comprehension: squares = [x * x for x in range(10)]

Filtering
Here we are calculating the same set of values as above but we are only keeping the even numbers. even_squares = [x * x for x in range(10) if x % 2 == 0 Returns : [0, 4, 16, 36, 64] If you wanted to do the same thing with a for-loop: even_squares = [] for x in range(10): if x % 2 == 0: even_squares.append(x * x)