List Comprehension in Python

List comprehensions are used for creating new lists from other iterables like lists, tuples, dictionaries, sets, and even in arrays and strings.

Syntax [ expression for item in iterable if condition]

Example: Squares of numbers 1..5.

Python

nums = [1, 2, 3, 4, 5]
squares = [x * x for x in nums]   # compute x*x for every x in nums
# output: [1, 4, 9, 16, 25] 

List comprehension is syntactic sugar. The following are equivalent:

Syntax

List comprehension:
squares = [x*x for x in nums]

Equivalent loop:
squares = []
for x in nums:
    squares.append(x * x) 

Example: Filtered comprehension (only evens from 0..9).

Python

evens = [x for x in range(10) if x % 2 == 0]   # keep x only when x%2==0
# output: [0, 2, 4, 6, 8]