Is it possible to specify the size of list at construction?

Steven Bethard steven.bethard at gmail.com
Tue Mar 1 15:56:34 EST 2005


Anthony Liu wrote:
> Yes, that's helpful.  Thanks a lot.
> 
> But what if I wanna construct an array of arrays like
> we do in C++ or Java:
> 
> myArray [][]
> 
> Basically, I want to do the following in Python:
> 
> myArray[0][1] = list1
> myArray[1][2] = list2
> myArray[2][3] = list3
> 
> How to do this, gurus?

You might be able to get by with:

py> arr = [[] for _ in range(10)]
py> arr
[[], [], [], [], [], [], [], [], [], []]

But perhaps not:

py> arr[0][1] = 1
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
IndexError: list assignment index out of range

If you know the default value, you might consider:

py> arr = [[0]*10 for _ in range(10)]
py> arr[0][1] = 1
py> arr
[[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 
0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 
0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 
0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

although if you're planning on doing this kind of stuff, you should 
definitely check out the numarray module.

Generally though, I find that a dict with tuple keys is the better 
solution here:

py> d = {}
py> d[0,1] = 1
py> d[2,3] = 1
py> d[0,1]
1
py> d.get((4, 5), 0)
0

STeVe



More information about the Python-list mailing list