Skip to content

List Comprehensions

List comprehensions allows elements of a list to be transformed given a specified condition.

even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
[0, 2, 4, 6, 8]

This operation can also be used to transform elements from a list to a dictionary structure.

transform_list = {x:x *2 for x in range(1,10) if x % 2 == 0}
print(transform_list)
{2: 4, 4: 8, 6: 12, 8: 16}

List comprehensions can include multiple for loops as well.

multiple_loops = [ (x,y) for x in range(1, 5) for y in range(x+1, 5)]
print(multiple_loops)
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]