1

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

6
  • strictly using the slice operator? Commented Aug 19, 2019 at 15:53
  • Yes, if possible Commented Aug 19, 2019 at 15:54
  • Hope it is possible? if not, please answer it as not possible. Commented Aug 19, 2019 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. Commented Aug 19, 2019 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]. Commented Aug 19, 2019 at 16:03

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

yes, using list compression we can do it.
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.

2 Comments

since numpy doest comes under python default package I can't accept this answer. very nice trick.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.