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]
1nums = [4, -7, 9, 1, -1, 8, -6]
2half_of_nums = [x/2 for x in nums] #[2, -3.5, 4.5, 0.5, -0.5, 4, -3]
3
4#optionally you can add an if statement like this
5half_of_positive_nums = [x/2 for x in nums if x>=0] #[2, 4.5, 0.5, 4]
1#example: removing common elements found in `a` from `b`.
2a = [1,2,3,4,5]
3b = [5,6,7,8,9]
4# desired output: [1,2,3,4]
5
6# gets each item found in `a` AND not in `b`
7print([i for i in a if i not in b])
1# List comprehension
2
3
4list_comp = [i+3 for i in range(20)]
5
6# above code is similar to
7
8for i in range(20):
9 print(i + 3)