Understanding Slicing

Understanding slicing

The syntax is:

a[start:stop]  # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array

There is also the step value, which can be used with any of the above:

a[start:stop:step] # start through not past stop, by step

The key point to remember is that the :stop value represents the first value that is not in the selected slice. So, the difference between stop and start is the number of elements selected (if step is 1, the default).

The other feature is that start or stop may be a negative number, which means it counts from the end of the array instead of the beginning. So:

a[-1]    # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items

Similarly, step may be a negative number:

a[::-1]    # all items in the array, reversed
a[1::-1] # the first two items, reversed
a[:-3:-1] # the last two items, reversed
a[-3::-1] # everything except the last two items, reversed

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

Relationship with the slice object

A slice object can represent a slicing operation, i.e.:

a[start:stop:step]

is equivalent to:

a[slice(start, stop, step)]

Slice objects also behave slightly differently depending on the number of arguments, similarly to range(), i.e. both slice(stop) and slice(start, stop[, step]) are supported.
To skip specifying a given argument, one might use None, so that e.g. a[start:] is equivalent to a[slice(start, None)] or a[::-1] is equivalent to a[slice(None, None, -1)].

While the :-based notation is very helpful for simple slicing, the explicit use of slice() objects simplifies the programmatic generation of slicing.

Not understanding slicing in Python

What is : in Python? It is an operator for slicing a list and it is an alias for slice(start, end, step) function.

How can I use it and how it works? When you use it with a list such as [1,2,3] like [1,2,3][0:2] you get all elements from 0th to first. In fact, 2 is excluded.

And please mind that array indices start from 0, so 1 is the 0th element of the list:

[1,2,3][0] == 1 # True

And if you want to get all elements you can use [1,2,3][0:3].

Two more points:

  1. There is another part: step like [start:end:step] and you can specify step size, for example [1,2,3,4][0:4:2] will give you [1,3]
  2. You can omit any part of a slice: [:4] means [0:4], [0:] means [0:last_index+1], and [:] means [0:last_index+1]

What is the meaning of a[:,1] in python slicing

Hy! @martin a[:,1:] is used to slice 2-dimensional NumPy array for example.

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

represent as

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

than a[:,1] == a[col[start] : col[end], row[start] : row[end]]

will be [[2,5]] means take both column and row at 1st index.

Understanding specific slice method

This is precisely how any Python programmer would write it.

list[:start] is all the elements from 0 (inclusive) to start (exclusive). list[end + 1:] is all the elements from index end + 1 to the end of the array. + concatenates them together.

what does [::-1] mean in python - slicing?

Slicing

  1. Negative numbers for start and stop mean "from the end". It's essianlly equivalent of len-value.
  2. Negative number for step means "in reverse order".
  3. Empty start means 0 i.e. 1st element.
  4. Empty stop means len. Stop parameter is exclusive!

So [::-1] means from 1st element to last element in steps of 1 in reverse order.


  1. If you have [start:stop] it's the same as step=1. So [:-1] it means all but last. again it's the last element exclusive. It's the same as [:-1:] or [0:-1:1].

If you have only start, it returns one element given by the index start. Thus [-1] means last element. Same as [len-1] would.

range

Range also has syntax start,stop,step but the step has a different meaning. Step is added repeatedly starting from start. So you start at 4, and go down by adding -1 until you hit stop, also exclusively. So range(5,0)[::-1] is equivalent to range(4,-1,-1). You can compute it.

Why interpreter says range(0,5)[::-1] => range(4, -1, -1)?

Python interpreter is smart enough to convert a slice of range into another range. This is an optimization, ranges are generators. They are dynamic, i.e. they don't hold all the elements in the memory at once. It the interpreter you are using worked step-by-step, it would have to generate whole list, just to be able to iterate in a reverse order. It's smarter to compute new generator.

How it is done, is explained in detail Łukasz'es answer.

Btw. you can force it to generate a list, and prevent from optimizing:

   range(0,5)[::-1]
=> range(4, -1, -1)
list(range(0,5))[::-1]
=> [4, 3, 2, 1, 0]

Understanding the slicing of NumPy array

The ending indices (the 3's in 0:3 and 1:3) are exclusive, not inclusive, while the starting indices (0 and 1) are in fact inclusive. If the ending indices were inclusive, then the output would be as you expect. But because they're exclusive, you're actually only grabbing rows 0, 1, and 2, and columns 1 and 2. The output is the intersection of those, which is equivalent to the output you're seeing.

If you are trying to get the data you expect, you can do myNumpyArray[:, 1:]. The : simply grabs all the elements of the array (in your case, in the first dimension of the array), and the 1: grabs all the content of the array starting at index 1, ignoring the data in the 0th place.



Related Topics



Leave a reply



Submit