9

I want to extract a part of a two-dimensional list (=list of lists) in Python. I use Mathematica a lot, and there it is very convenient to write

matrix[[2;;4,10;;13]] 

which would extract the part of the matrix which is between the 2nd and 4th row as well as the 10th and 13th column.

In Python, I just used

[x[firstcolumn:lastcolumn+1] for x in matrix[firstrow:lastrow+1]]

Is there also a more elegant or efficient way to do this?

1 Answer 1

21

What you want is numpy arrays and the slice operator :.

>>> import numpy

>>> a = numpy.array([[1,2,3],[2,2,2],[5,5,5]])
>>> a
array([[1, 2, 3],
       [2, 2, 2],
       [5, 5, 5]])

>>> a[0:2,0:2]
array([[1, 2],
       [2, 2]])
Sign up to request clarification or add additional context in comments.

1 Comment

@user1447622 - you're welcome! If the answer works, you should accept it by clicking on the checkmark (unless you're waiting to see if you get other answers, which is perfectly fine - I just thought I'd point it out in case you didn't know how it works, since you're a new user)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.