1
\$\begingroup\$

Is there any way I can make this function more inline?

def nDimensionalArray(n, s):
    x = 0
    for i in range(n):
        x = [x for j in range(s[i])]
    return x
\$\endgroup\$
3
\$\begingroup\$

You didn't write a docstring (which you should have done) or explain your function (which you should also have done), but it looks like n is supposed to be the same as the length of s. If so, why should n have to be specified?

Your function has some unintuitive behaviour:

>>> matrix = nDimensionalArray(3, [1,2,3])
>>> matrix
[[[0], [0]], [[0], [0]], [[0], [0]]]
>>> matrix[0][0][0] = 1
>>> matrix
[[[1], [1]], [[1], [1]], [[1], [1]]]

Changing one element changes everything! I assume that that is unintentional. If it is intentional, then it needs to be clearly documented.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.