1
2# set comprihension
3
4{i+1 for i in range(20)}
5
6{(i,j) for j in range(4,7) for i in range(6,8)}
7
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)
1Squaring List elements:
2 By loop:
3
4lst = [1, 2, 3]
5l =[]
6for i in lst:
7 lst.append(i*i)
8print(l)
9
10
11 By List Comprehension:
12
13lst = [1, 2, 3]
14l = [x*x for x in lst]
15print(l)
16
1
2 fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
3
4newlist = [x
5 for x in fruits if "a" in x]
6
7print(newlist)