Yorian
Yorian

Reputation: 2062

What does python slicing syntax [o:,:] mean

Just a small and probably very simple question. Someone gave me the following line of code:

im = axs[0,i].pcolormesh(imgX[o:,:], imgY[o:,:], img.mean(-1)[o:,:], cmap='Greys')

I know ":" means everything in that column or row (or array depth, depending on how you look at it). But what does "o:" mean?

Upvotes: 4

Views: 294

Answers (2)

Davidmh
Davidmh

Reputation: 3865

o is a variable like any other (but with a very bad name, as it can be confused with a zero).

[o:, :] means "all the elements from the first axis starting in the element o, and all in the second axis. In your particular case, the image will show only the rows from o to the bottom.

I want to add that in this case, you are getting a view, i.e., a reference to the original array, so the data is not actually copied.

Upvotes: 2

user2864740
user2864740

Reputation: 62015

The following is not related to the usage, but shows how the operation "is parsed".


class X:
   def __getitem__(self, index):
       return index

X()[:,:]
>> (slice(None,None,None), slice(None,None,None))

And with different values for clarity:

X()[0, 1:, 3:4, 5:6:7]
>> (0, slice(1,None,None), slice(3,4,None), slice(5,6,7))

So, with that in mind img[o:,:] is like img[o:, :] is like

img.__getitem__( (slice(o,None,None), slice(None,None,None)) )

Upvotes: 3

Related Questions