In python, we have a very neat way of creating lists.
The list comprehension syntax is:
<list> = [<expression> for <item> in <iterable>]
<list> = [<expression> for <item> in <iterable> if <condition>]
The if part is optional. The iterable object can be a string, list, tuple, dictionary, set, range object, etc.
Let’s see some examples. range(i) object gives us numbers from 0 up to i (exclusive)
x = [ i for i in range(10) ]; print(x)
x = [ i**2 for i in range(10) ]; print(x)
x = [ i**2 for i in range(10) if i%3 != 0 ]; print(x) #exclude multiples of 3
We can use more than one for statement in one comprehension.
x = [ (i,j) for i in range(1,4) for j in range(1,4) if i!=j ]; print(x)
#create 3x3 of unequal pairs
If we have a list of lists, we can extract all elements to a single list.
i iterates over x once, and ii iterates over elements of i 4 times.
x = [ ['a','b','c'], [1,2,3], ['x','y','z'], [4,5,6] ]
y = [ ii for i in x for ii in i ]; print(y)
Let’s transpose a matrix using list comprehensions:
x = [ [1,2,3],
[4,5,6],
[7,8,9],
[10,11,12] ]
#we want 1,4,7,10 in a list. x[0][0], x[1][0], x[2][0], x[3][0]
#then 2,5,8,11. x[0][1], x[1][1], x[2][1], x[3][1]
y = [ [row[i] for row in x] for i in range( len(x[0]) ) ]; print(y)