Skip to content
Advertisement

Multidimensional array in Python

I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:

JavaScript

Further values will be created bei loops and written into the array.

How do I instantiate the array?

PS: There is no matrix multiplication involved…

Advertisement

Answer

You can create it using nested lists:

JavaScript

If it has to be dynamic it’s more complicated, why not write a small class yourself?

JavaScript

This can be used like this:

JavaScript

I’m sure one could implement it much more efficient. :)

If you need multidimensional arrays you can either create an array and calculate the offset or you’d use arrays in arrays in arrays, which can be pretty bad for memory. (Could be faster though…) I’ve implemented the first idea like this:

JavaScript

Can be used like this:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement