Indexing list of lists

David C. Fox davidcfox at post.harvard.edu
Tue Sep 23 10:41:39 EDT 2003


Hilde Roth wrote:

>>Only if all the sublists are of the same length, which is guaranteed for 
>>a multi-dimensional array, but not for a list of lists.
> 
> 
> This is a red herring.

No, it's not.  It is a hint that, despite the similarity of notation 
between Matrix[i][j] and NestedList[i][j], there is something 
fundamentally different between the two.  See below for another example.

>  
> 
>>What do you expect a[;1] to return if a = [[], [1, 2, 3], [4], 5]?
> 
> 
> Whatever error python returns if you ask, e.g., for (1 2 3)[4].
> 
> Hilde

Okay, here's a better example which I thought of just after I posted my 
previous reply:

Given

   x = [[1, 2], [3, 4]]

the statement

   x[0] = [5, 6]

will result in a nested list x = [ [5, 6], [3, 4] ].  If you think of x 
as a multi-dimensional array represented by a nested list, then I've 
just replaced a row of the original array

1 2
3 4

with a new row, yielding

5 6
3 4

If we had an x[;0] notation, then you would expect to be able to do the 
same thing to replace a column:

   x[;0] = [7, 8]

Unfortunately, there is no pre-existing list representing the first 
column of x, so x[;0] has to return a new list [1, 3], and assigning to 
that new list has no affect on x.

Again, my point is that nested lists are a fundamentally different 
structure than multi-dimensional arrays.  For simple things like 
x[i][j], you can use a nested list to represent a multi-dimensional 
array, but if you actually want to manipulate a two-dimensional array 
like a matrix, you are better off using a class designed for that 
purpose, like the ones defined in Numeric Python.

David





More information about the Python-list mailing list