Assuming your matrix is list of lists, you can use zip()
-
from random import randint
a = [[randint(1, 10) for _ in range(3)] for _ in range(3)]
b = [[randint(1, 10) for _ in range(3)] for _ in range(3)]
c = [list(zip(x, y)) for x, y in zip(a, b)]
>>> a
[[8, 4, 1], [4, 3, 4], [2, 5, 5]]
>>> b
[[2, 2, 1], [6, 1, 7], [10, 3, 5]]
>>> c
[[(8, 2), (4, 2), (1, 1)], [(4, 6), (3, 1), (4, 7)], [(2, 10), (5, 3), (5, 5)]]
If you don't want to use zip
, using list comprehension -
c = [list((a[i][j], b[i][j]) for j in range(len(a[0]))) for i in range(len(a))]
Both ways work even when a
and b
is not square matrix as long as the dimensions of both matrices are identical.