Python: How to type a multidimensional array

Published: 2019-11-18 13:12:33 -0700 -0700

Reading time: 1 mins (149 words)

Tags: python typing types array list


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?


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)]

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

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.

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus