[Tutor] Accesing "column" of a 2D list

Kent Johnson kent37 at tds.net
Tue Aug 21 12:40:45 CEST 2007


Ian Witham wrote:
> This looks like a job for List Comprehensions!
> 
>  >>> list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>  >>> new_list = [item[1] for item in list]
>  >>> new_list
> [2, 5, 8]
>  >>>

Alternately, if you want *all* columns, you can use zip() to transpose 
the lists:

In [1]: lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [2]: zip(*lst)
Out[2]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

PS. Don't use 'list' as the name of a list, it shadows the builtin 
'list' which is the <type> of list. Similarly, avoid str, dict, set and 
file as names.

Kent

> looks good?
> 
> Ian
> 
> On 8/21/07, *Orest Kozyar* <orest.kozyar at gmail.com 
> <mailto:orest.kozyar at gmail.com>> wrote:
> 
>     I've got a "2D" list (essentially a list of lists where all sublists
>     are of
>     the same length).  The sublists are polymorphic.  One "2D" list I
>     commonly
>     work with is:
> 
>     [ [datetime object, float, int, float],
>       [datetime object, float, int, float],
>       [datetime object, float, int, float] ]
> 
>     I'd like to be able to quickly accumulate the datetime column into a
>     list.
>     Is there a simple/straightforward syntax (such as list[:][0]) to do
>     this, or
>     do we need to use a for loop?  I expect what I have in mind is
>     similar to
>     the Python array type, except it would be polymorphic.
> 
>     Thanks,
>     Orest
> 
>     _______________________________________________
>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list