zonksoft
zonksoft

Reputation: 2429

Extract part of 2D-List/Matrix/List of lists in Python

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?

Upvotes: 9

Views: 30474

Answers (1)

weronika
weronika

Reputation: 2629

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]])

Upvotes: 21

Related Questions