1# All of the possibilies that can be done with the List Comprehension
2
3vec = [-4, -2, 0, 2, 4]
4# create a new list with the values doubled
5
6doubled = [x*2 for x in vec]
7# [-8, -4, 0, 4, 8]
8
9# filter the list to exclude negative numbers
10greater_thatn_0 = [x for x in vec if x >= 0]
11# output [0, 2, 4]
12
13# apply a function to all the elements
14positive = [abs(x) for x in vec]
15# output [4, 2, 0, 2, 4]
16
17# call a method on each element
18freshfruit = [' banana', ' loganberry ', 'passion fruit ']
19fruits_nospaces = [weapon.strip() for weapon in freshfruit]
20# output ['banana', 'loganberry', 'passion fruit']
21
22# create a list of 2-tuples like (number, square)
23squares = [(x, x**2) for x in range(6)]
24# output [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
25
26# the tuple must be parenthesized, otherwise an error is raised
27# error = [x, x**2 for x in range(6)]
28 # error = [x, x**2 for x in range(6)]
29 ^
30# SyntaxError: invalid syntax
31
32# flatten a list using a listcomp with two 'for'
33vec = [[1,2,3], [4,5,6], [7,8,9]]
34unpacking_tuple = [num for elem in vec for num in elem]
35# output [1, 2, 3, 4, 5, 6, 7, 8, 9]
1matrix = [[1, 2], [3,4], [5,6], [7,8]]
2transpose = [[row[i] for row in matrix] for i in range(2)]
3print (transpose)
1[output_expression for element in list if condition]Code language: Python (python)