1

I'm trying to do what I think should be simple:

I make a 2D list:

a = [[1,5],[2,6],[3,7]]

and I want to slide out the first column and tried:

1)

a[:,0]
...
TypeError: list indices must be integers or slices, not tuple

2)

a[:,0:1]
...
TypeError: list indices must be integers or slices, not tuple

3)

a[:][0]
[1, 5]

4)

a[0][:]
[1, 5]

5) got it but is this the way to do it?

 aa[0] for aa in a

Using numpy it would be easy but what is the Python way?

martineau
  • 119,623
  • 25
  • 170
  • 301
yoni
  • 69
  • 2
  • 6
  • 1
    `[ aa[0] for aa in a ]` looks fine to me – OneCricketeer Mar 22 '17 at 07:21
  • Possible duplicate of [Get the nth element from the inner list of a list of lists in Python](http://stackoverflow.com/questions/13188476/get-the-nth-element-from-the-inner-list-of-a-list-of-lists-in-python) – Himaprasoon Mar 22 '17 at 09:58

3 Answers3

5

2D slicing like a[:, 0] only works for NumPy arrays, not for lists.

However you can transpose (rows become columns and vice versa) nested lists using zip(*a). After transposing, simply slice out the first row:

a = [[1,5],[2,6],[3,7]]
print zip(*a)           # [(1, 2, 3), (5, 6, 7)]
print list(zip(*a)[0])  #  [1, 2, 3]
Nils Werner
  • 34,832
  • 7
  • 76
  • 98
0

Use [x[0] for x in a] is the clear and proper way.

Chuancong Gao
  • 654
  • 5
  • 7
0

What you are trying to do in numerals 1 and 2 works in numpy arrays (or similarly with pandas dataframes), but not with basic python lists. If you want to do it with basic python lists, see the answer from @cricket_007 in the comments to your question.

One of the reasons to use numpy is exactly this - it makes it much easier to slice arrays with multiple dimensions

jberrio
  • 972
  • 2
  • 9
  • 20