Do you have a good explanation (with references) on Python's slice notation? To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it and am looking for a good guide.
|
|
It's pretty simple really:
There is also the
The key point to remember is that the The other feature is that
Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for |
|||||||||||||||||||||
|
|
The tutorial talks about it: http://docs.python.org/tutorial/introduction.html#strings (Scroll down a bit until you get to the part about slicing.) The ASCII art diagram is helpful too for remembering how slices work:
|
|||||||||||||||||
|
|
Enumerating the possibilities allowed by the grammar:
Of course, if Extended slicing (with commas and ellipses) are mostly used only by special data structures (like Numpy); the basic sequences don't support them.
|
|||||
|
|
The answers above don't discuss slice assignment:
This may also clarify the difference between slicing and indexing. |
|||||||||
|
|
And a couple of things that weren't immediately obvious to me when I first saw the slicing syntax:
Easy way to reverse sequences! And if you wanted, for some reason, every second item in the reversed sequence:
|
|||||||||
|
|
Found this great table at http://wiki.python.org/moin/MovingToPythonFromOtherLanguages
|
|||
|
|
|
After using it a bit I realise that the simplest description is that it is exactly the same as the arguments in a for loop...
any of them are optional
then the negative indexing just needs you to add the length of the string to the negative indices to understand it. This works for me anyway... |
|||||
|
|
In python 2.7 Slicing in python [a:b:c] len = length of string, tuple or list c -- default is +1. sign of c indicates forward or backward, absolute value of c indicates steps. Default is forward with step size 1. Positive means forward, negative means backward. a -- when c is positive or blank, default is 0. when c is negative, default is -1. b -- when c is positive or blank, default is len. when c is negative, default is -(len+1). Understanding index assignment is very important. In forward direction, starts at 0 and ends at len-1 In backward direction, starts at -1 and ends at -len when you say [a:b:c] you are saying depending on sign of c (forward or backward), start at a and end at b ( excluding element at bth index). Use the indexing rule above and remember you will only find elements in this range -len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1 but this range continues in both directions infinitely ...,-len -2 ,-len-1,-len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1, len, len +1, len+2 , .... e.g.
if your choice of a , b and c allows overlap with the range above as you traverse using rules for a,b,c above you will either get a list with elements (touched during traversal) or you will get an empty list. One last thing: if a and b are equal , then also you get an empty list
|
|||||||||
|
|
I use the "an index points between elements" method of thinking about it myself, but one way of describing it which sometimes helps others get it is this:
X is the index of the first element you want. |
|||||
|
|
I find it easier to remember how it's works, then I can figure out any specific start/stop/step combination. It's instructive to understand
Begin from The thing to remember about negative step is that Sequence slicing is same, except it first normalizes negative indexes, and can never go outside the sequence:
Don't worry about the Normalizing negative indexes first allows start and/or stop to be counted from the end independently: |
||||
|
|
|
I'm aiming for the complete canonical answer here. Python slicing is a computationally fast way to methodically access parts of your data. In my opinion, to be even an intermediate Python programmer, it's one aspect of the language that it is necessary to be familiar with. Important DefinitionsTo begin with, let's define a few terms:
How Indexing WorksYou can make any of these positive or negative numbers. The meaning of the positive numbers is straightforward, but for negative numbers, just like indexes in Python, you count backwards from the end for the start and stop, and for the step, you simply decrement your index. This example is from the documentation's tutorial, but I've modified it slightly to indicate which item in a sequence each index references:
How Slicing WorksTo use slice notation with a sequence that supports it, you must include at least one colon in the square brackets that follow the sequence (which actually implement the Slice notation works like this:
And recall that there are defaults for start, stop, and step, so to access the defaults, simply leave out the argument,
When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on") Explanation:The full notation is
and to substitute the defaults:
But the colon,
And clearing them is with:
Give your slices a descriptive name!You may find it useful to separate forming the slice from passing it to the However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:
The second argument, You can then pass the slice object to your sequence:
Memory Considerations:Since slices of Python lists create new objects in memory, another important function to be aware of is
The fact that list slices make a copy is a feature of lists themselves. If you're slicing advanced objects like a Pandas DataFrame, it may return a view on the original, and not a copy. |
|||||
|
hope this will help you to model the list in Python reference:http://wiki.python.org/moin/MovingToPythonFromOtherLanguages |
|||
|
|
|
You can also use slice assignment to remove one or more elements from a list:
|
||||
|
|
|
Python slicing notation:
The notation extends to (numpy) matrices and multidimensional arrays. For example, to slice entire columns you can use:
Slices hold references, not copies, of the array elements. If you want to make a separate copy an array, you can use |
|||||
|
|
This is just for some extra info... Consider the list below
Another trick for reversing a list may be :
|
||||
|
|
|
As a general rule, writing code with a lot of hardcoded index values leads to a readability and maintenance mess. For example, if you come back to the code a year later, you’ll look at it and wonder what you were thinking when you wrote it. The solution shown is simply a way of more clearly stating what your code is actually doing. In general, the built-in slice() creates a slice object that can be used anywhere a slice is allowed. For example:
If you have a slice instance s, you can get more information about it by looking at its s.start, s.stop, and s.step attributes, respectively. For example:
|
|||
|
|
|
If you prefer a video and voiceover instead, the guy in the Google Python course (click here) talks about slice syntax and some of its practical uses, starting from the time index 42:34; the link will take you to that point. |
||||
|
|
|
To get a certain piece of an iterable (like a list), here is an example:
In this example, a positive number for number 1 is how many components you take off the front. A negative number is the exact opposite, how many you keep from the end. A positive number for number 2 indicates how many components you intend to keep from the beginning, and a negative is how many you intend to take off from the end. This is somewhat counter intuitive, but you are correct in supposing that list slicing is extremely useful. |
|||||
|
You can run this script and experiment with it, below is some samples that I got from the script.
When using a negative step, notice that the answer is shifted to the right by 1. |
|||
|
|
protected by Jon Clements Feb 8 '13 at 9:20
Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?