0

Example:

a = [[1,2,3],[4,5,6],[7,8,9]]

By doing something like a[:][0], I expect it to give me 1st elements in each row [1,4,7]

However, I get [1,2,3]. I can always make a function to do it.

def column(array,index):
    result = []
    for row in array:
        result.append(row[index])
    return result

But I was wondering: is there a smarter way of doing it?

John Y
  • 14,123
  • 2
  • 48
  • 72

5 Answers5

3

The de facto standard way of manipulating arrays in such a way is to use the dedicated NumPy package.

Things work the way you want, with NumPy:

>>> import numpy
>>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a[:,0]
array([1, 4, 7])

In fact, the purpose of NumPy is to provide powerful array manipulations.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
3

a[:][0] doesn't work because a[:] gives a copy of a. [0] then gets the first value from that copy, which is [1,2,3]

Instead use a list comprehension:

a = [[1,2,3],[4,5,6],[7,8,9]]
col = [row[0] for row in a] # => [1,4,7]
Community
  • 1
  • 1
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
2

You can also use a one line for loop, but it is the same as what you already do:

a = [[1,2,3],[4,5,6],[7,8,9]]
result = [item[0] for item in a]
aweis
  • 5,350
  • 4
  • 30
  • 46
2

Use zip():

>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> zip(*a)[0]
(1, 4, 7)

But note that zip builds tuples, which may require you to convert back to lists depending on your application.

Russell Borogove
  • 18,516
  • 4
  • 43
  • 50
  • Note that you are creating N arrays here, unlike the list comprehension. And not everyone will know what zip() does, but it is a lot smaller :). – James Antill Sep 28 '11 at 20:25
  • More specifically, `zip` builds a list of tuples (as opposed to a tuple of tuples), or an iterator of tuples on Python 3. – agf Sep 28 '11 at 20:27
  • @Russell Borogove: I would strongly advise against such a solution: what you want to do (extract the first element) is obfuscated by the `zip()`, which implies for most Python programmers that the program really needs to keep all the original data, but in a different structure; this is actually a waste of memory and execution time. Furthermore, this does not work in Python 3, because the result of `zip()` is a generator, in Python 3, so you would need `list(zip(*a))[0]`. The list comprehension approach is both extremely explicit and standard. – Eric O. Lebigot Sep 29 '11 at 07:05
  • @JamesAntill, @EOL - you're right about the performance aspect, but something about the phrasing of the question smelled to me like the broader use of `zip()` for transposition might be handy. – Russell Borogove Sep 29 '11 at 08:51
1

A bit of list comprehension will do the job:

a = [[1,2,3],[4,5,6],[7,8,9]]
col = [c[0] for c in a]

No idea of speed implications.

John Keyes
  • 5,479
  • 1
  • 29
  • 48