0

I have 2-D matrix of size n, I want to get the entire n-1th column values into another list. For example,

a = [[1, 2], [3, 4], [5, 6]]
a[:][0] // return [1,2]

how to get 1,3,5 for above a 2-D array into a list using slice operator

ajayramesh
  • 3,576
  • 8
  • 50
  • 75
  • strictly using the slice operator? – user1984 Aug 19 '19 at 15:53
  • Yes, if possible – ajayramesh Aug 19 '19 at 15:54
  • Hope it is possible? if not, please answer it as not possible. – ajayramesh Aug 19 '19 at 15:55
  • 1
    I'm not aware of a solution with the slice operator (admittedly I don't have much experience with python). I wold recommend list comprehensions. – user1984 Aug 19 '19 at 16:02
  • 1
    If you aren't tied to using lists strictly, you might want to consider numpy, esp if you only have numbers and all rows have the same number of elements. You can slice like this: `a[:, -2]`. – busybear Aug 19 '19 at 16:03
  • @busybears - Yes, I simplified to numbers, but in our case it can have any data type 2-D array. Thank you for your comments, I accept the answer as it is not possible for 2-D array/list in python. – ajayramesh Aug 19 '19 at 16:33

2 Answers2

1

To my knowledge, the array slice operator is not suited for what you're looking for.

I would recommend python's list comprehensions.

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

result = [x[0] for x in a]
print(result)
user1984
  • 5,990
  • 2
  • 13
  • 32
1

You can do this using the numpy library:

import numpy

a = np.array([[1, 2], [3, 4], [5, 6]])
result = a[:, 0]   # Returns a 1-D numpy array [1, 3, 5]

More advanced indexing and slicing options can be found here.

GZ0
  • 4,055
  • 1
  • 10
  • 21
  • since numpy doest comes under python default package I can't accept this answer. very nice trick. – ajayramesh Aug 19 '19 at 16:30
  • 1
    That's fine. You can select any answer that is best for you. But if your code needs to do lots of matrix processing you may want to consider using numpy. – GZ0 Aug 19 '19 at 16:39