Matrixes and Comprehension Expressions in Python

Matrixes and Comprehension Expressions in Python

We can nesting in Python. It’s especially useful for lists. We can get the 3 x 3 matrix:

>>> e = [[10,20,30], [40,50,60], [70,80,90]]
>>> e
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
>>>

We can use it in the following way:

>>> e[2]
[70, 80, 90]

We have one row only, but we can do that:
>>> e[2][2]
90
>>>
But what with columns? We need to extract the second column in our matrix.

>>> f = [g[2] for g in e]
>>> f
[30, 60, 90]
>>> h = [g[0] for g in e]
>>> h
[10, 40, 70]
>>>
We can even do more with comprehension:

>>> f = [g[2] * 3 + 4 for g in e]
>>> f
[94, 184, 274]
>>> h = [g[0] / 4 – 1 for g in e]
>>> h
[1.5, 9.0, 16.5]
>>>

We can create a generator using a matrix:

>>> i = (sum(j) for j in e)
>>> i
<generator object <genexpr> at 0x00D078F0>
>>> next(i)
60
>>> next(i)
150
>>> next(i)
240
>>>

And we can do many other operations with matrixes.

1 thought on “Matrixes and Comprehension Expressions in Python

Leave a comment