Select column from a list

Xavier Ho contact at xavierho.com
Fri Aug 28 03:55:50 EDT 2009


On Fri, Aug 28, 2009 at 5:45 PM, hoffik <beorn at seznam.cz> wrote:

> 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.


As far as I know though, you will have to loop through this if you built
your matrix with nested lists.

i.e.:

li = [[1,2],[3,4]]
result = []
for row in li:
    result.append(row[0])
# result == [1, 3]


> For example I have list called 'values'.
> When I write 'values[0]' or 'values[0][:]' I'll get the first row.
> But when I write 'values[:][0]' I won't get the first column, but the first
> row again! I can't see why.


Let's say values = [[1,2][3,4]].
values[:] returns the entire values list, from beginning to end. So you end
up what you started with.
And, of course, values[:][0] is the same as values[0].

In fact:

>>> li[:][:][:][0] is li[0]
True

It's... a very interesting behaviour, to say the least.

You might be able to get a proper matrix behaviour using NumPy, (which I
never used, so I'm just throwing it out there as a guess) or you might have
to write your own iterator for later reuse.

Cheers,
Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090828/7e515a80/attachment-0001.html>


More information about the Python-list mailing list