Select column from a list

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Aug 28 05:06:31 EDT 2009


hoffik a écrit :
> Hello,
> 
> I'm quite new in Python and I have one question. I have a 2D matrix of
> values stored in list (3 columns, many rows).  I wonder if I can select one
> column without having to go through the list with 'for' command.

Lists don't have columns. What you have is a list of lists (and FWIW, in 
your case, it should be a list of tuples since obviously these are 
fixed-size items where position is meaningfull).

> For example I have list called 'values'.
> When I write 'values[0]' or 'values[0][:]' I'll get the first row.

Not exactly. In the first case, you have a reference to values[0], in 
the second case a _copy_ of values[0]

 >>> alist = [[1, 2, 3], [4, 5, 6]]
 >>> ref = alist[0]
 >>> copy = alist[0][:]
 >>> ref is alist[0]
True
 >>> copy is alist[0]
False
 >>> copy[0] = 999
 >>> copy
[999, 2, 3]
 >>> alist
[[1, 2, 3], [4, 5, 6]]
 >>> ref
[1, 2, 3]
 >>> ref[0] = 888
 >>> alist
[[888, 2, 3], [4, 5, 6]]
 >>>


> But when I write 'values[:][0]' I won't get the first column, but the first
> row again! I can't see why.


alist[:] returns a copy the whole list. As I said, lists don't have 
"columns".

So yes, given your data structure, you do have to iterate over the outer 
list to collect items at specific positions of the inner lists (or tuples).

Depending on the size of your dataset, the frequency of such operation 
in your code, and required perfs, you can either

* just do the simplest thing, ie:

   first_column_items = [row[0] for row in values]

* try to find a more suited datastructure

* of just use the most appropriate tool for set operations, which is a 
relational database. FWIW, sqlite doesn't require any server setup, and 
can even be used with in-memory databases if you don't need persistance.

HTH



More information about the Python-list mailing list