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# without using List comprehension
2numbers = [1,2,3]
3new_list = []
4
5for num in numbers:
6 new_list.append(num * 2)
7print(new_list)
8
9# List comprehension
10new_list_compre = [num * 2 for num in numbers]
11print(new_list_compre)
12
13# List comprehension using range
14double_list = [i*2 for i in range(1,5)]
15print(double_list)
16
17# conditional List Comprehensions
18names = ['Alex', 'Beth', 'Caroline', 'Dave', 'Eleanor', 'Freddie']
19# getting names less than 5 letters
20short_names = [name for name in names if len(name) < 5]
21print(short_names)
22