Matrix (list-in-list), how to get a column?

Peter Otten __peter__ at web.de
Thu Oct 21 12:19:51 EDT 2004


Arvid Andersson wrote:

> I have some data that looks like this:
> data = [[1, 2], [3, 4], [5, 6]]
> 
> I want to send columns 1 and 2 to a function
> as two variables, say "plot(col1,col2)".

In the general case list comprehensions are the way to go, but for the
problem specified above you can use a neat zip() trick, assuming that
plot() also accepts tuples instead of lists:

 >>> def plot(col1, col2): # plots nothing, but shows its arguments
...     print "col1", col1
...     print "col2", col2
...
>>> data = [[1, 2], [3, 4], [5, 6]]
>>> plot(*zip(*data))
col1 (1, 3, 5)
col2 (2, 4, 6)

The star prefix feeds the items in the following list as arguments to the
function, so zip(*[[1, 2], [3, 4]]) is the same as zip([1, 2], [3, 4]),
which in turn gives you [(1, 3), (2, 4)] as the result. 
The same technique can then be repeated with plot().

Peter






More information about the Python-list mailing list