from functools import reduce
def shape(flat, dims):
    subdims = dims[1:]
subsize = reduce(operator.mul, subdims, 1)
if dims[0] * subsize != len(flat):
    raise ValueError('Size does not match or invalid')
if not subdims:
    return flat
return [shape(flat[i:i + subsize], subdims) for i in range(0, len(flat),
    subsize)]
Read flat list into multidimensional array/matrix in python