Indexing list of lists

Peter Otten __peter__ at web.de
Tue Sep 16 17:51:56 EDT 2003


Hilde Roth wrote:

> This may have been asked before but I can't find it. If I have
> a rectangular list of lists, say, l = [[1,10],[2,20],[3,30]], is
> there a handy syntax for retrieving the ith item of every sublist?
> I know about [i[0] for i in l] but I was hoping for something more
> like l[;0].

If efficiency is not an issue and/or you need 
[item[index] for item in theList] for more than one index at a time, you can
do:

>>> s = [[1,2],[3,4]]
>>> t = zip(*s)
>>> t
[(1, 3), (2, 4)]
>>> t[1]
(2, 4)
>>>

This creates a transposed (?) copy of the "matrix". The side effect of
creating tupples instead of inner lists should do no harm if you need only
read access to the entries.

Peter




More information about the Python-list mailing list