# Python, Simple with Explanation

• Collect the values of the array A, and then put them into the answer of size `nR x nC`.

``````def matrixReshape(self, A, nR, nC):
if len(A) * len(A[0]) != nR * nC:
return A

vals = (val for row in A for val in row)
return [[vals.next() for c in xrange(nC)] for r in xrange(nR)]
``````

Alternative solution without generators:

``````def matrixReshape(self, A, nR, nC):
if len(A) * len(A[0]) != nR * nC:
return A

vals = [val for row in A for val in row]
ans = [[None] * nC for _ in xrange(nR)]
i = 0
for r in xrange(nR):
for c in xrange(nC):
ans[r][c] = vals[i]
i += 1
return ans``````

• @awice May I ask why you use nR, nC instead of just R, C ? I'm a beginner of python, can you explain to me? Thanks.

• @Houjue I used nR and nC for "new R" and "new C", because I wanted to reserve R, C for A. Typically in a 2D matrix problem I always write "R, C = len(A), len(A[0])" at the top, except I omitted it in this editorial.

• The Generator solution is sooooooo coooooooooool. ~~~~~~~

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.