Chucky Chan
Chucky Chan

Reputation: 75

Printing a column in an matrix without numpy

I'm really new to programming, so I apologize if this is a really simple question, but i've been trying to print the first column in a matrix without the use of numpy, however it prints like so:

matrix = \
[[0, 1],
 [3, 7],
 [9, 4],
 [10, 3]]

print matrix[0:3][0]
[0, 1] 

I've also tried:

print matrix[:][0]
[0, 1]

print matrix[:3]
[[0, 1], [3, 7], [9, 4]]

print matrix[:3][0]
[[0, 1], [3, 7], [9, 4]]

The answer I'm trying to achieve is:

print matrix[code]
0, 3, 9, 10

or similar.

Upvotes: 4

Views: 5587

Answers (2)

Gareth Latty
Gareth Latty

Reputation: 88977

What you have is a list of lists - so there is no concept of a column there. There are two ways to do this, one is (as Pavel Anossov's answer shows) is to use a list comprehension.

One is to use zip() which can be used to transpose an iterable:

>>> list(zip(*matrix))
[(0, 3, 9, 10), (1, 7, 4, 3)]

I've made it a list here to make it easier to show the output. Note in 2.x, zip() gives a list rather than an iterator (although a lazy version is available as itertools.izip()).

Generally, I would use zip() if you plan on working with more than one column, and the list comprehension if you only need one.

Upvotes: 6

Pavel Anossov
Pavel Anossov

Reputation: 62888

This is impossible with slicing without numpy. You can use a list comprehension:

print [row[0] for row in matrix]

Upvotes: 4

Related Questions