A list is a built-in data type. It can be witten as a list of comma-separated items between square brackets. Items can be heterogenous. “Heterogenous” means items in a list are of different types.
list_homogenous1 = [1, 2, 3, 4, 5]
print(list_homogenous1)
## [1, 2, 3, 4, 5]
list_homogenous2 = ["a", "b", "1", "2"]
print(list_homogenous2)
## ['a', 'b', '1', '2']
list_heterogenous = ["a", "b", 1, 2]
print(list_heterogenous)
## ['a', 'b', 1, 2]
Python doesn’t have a built-in type for matrices but you can treat a list of lists as a matrix.
A = [[1,2,3,4,5],
[1,2,3,4,5],
[1,2,3,4,5]]
print(A)
## [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
B = [[9,8,7,6,5],
[9,8,7,6,5],
[9,8,7,6,5]]
print(B)
## [[9, 8, 7, 6, 5], [9, 8, 7, 6, 5], [9, 8, 7, 6, 5]]
Let’s add the two matrices using nested loops. The code is a little complicated one like this.
result = [[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
# iterate through rows
for i in range(len(A)):
# iterate through columns
for j in range(len(A[0])):
result[i][j] = A[i][j] + B[i][j]
for x in result:
print(x)
## [10, 10, 10, 10, 10]
## [10, 10, 10, 10, 10]
## [10, 10, 10, 10, 10]
NumPy is a package for scientific computing which has support for N-dimensional array object. It is much easier to add the above two matrices with NumPy functions.
import numpy as np
A_array = np.array(A)
B_array = np.array(B)
AB_added = A_array +B_array
AB_added
## array([[10, 10, 10, 10, 10],
## [10, 10, 10, 10, 10],
## [10, 10, 10, 10, 10]])