Python: How to type a multidimensional array

Date: 2019-11-19 | python | typing | types | array | list


problem

I have a function that returns a multidimensional array (in Python typed as List) and am trying to add typing to it. How do I type this 3D array in Python?

solution

When you think about it, a multidimensional array (whether 2D, 3D, or even more D) is just nested lists of lists. Thus, for each dimension in our List, we just have to show that there's another List in there.

Here's some code:

from typing import List

my_1d_array: List[int] = [i for i in range(1, 10)]
print(my_1d_array) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

my_2d_array: List[List[int]] = [my_1d_array for i in range(1, 10)]
print(my_2d_array)

my_3d_array: List[List[List[int]]] = [my_2d_array for i in range(1, 10)]
print(my_3d_array)

did this help?

I regularly post about tech topics I run into. You can get a periodic email containing updates on new posts and things I've built by subscribing here.

Subscribe for Email Updates

* indicates required