Indexing and Slicing
- slice(start, stop[, step])
|The object that you want to extract a "sub-object" from|
|The index of |
|The (non-inclusive) index of |
|Allows you to select only every |
You can unify the concept of slicing strings with that of slicing other sequences by viewing strings as an immutable collection of characters, with the caveat that a unicode character is represented by a string of length 1.
In mathematical notation you can consider slicing to use a half-open interval of
[start, end), that is to say that the start is included but the end is not. The half-open nature of the interval has the advantage that
len(x) > =
n, while the interval being closed at the start has the advantage that
x is a list with
len(x) >= n, thus keeping consistency between indexing and slicing notation.
For any iterable (for eg. a string, list, etc), Python allows you to slice and return a substring or sublist of its data.
Format for slicing:
startis the first index of the slice. Defaults to 0 (the index of the first element)
stopone past the last index of the slice. Defaults to len(iterable)
stepis the step size (better explained by the examples below)
In addition, any of the above can be used with the step size defined:
Indices can be negative, in which case they're computed from the end of the sequence
Step sizes can also be negative, in which case slice will iterate through the list in reverse order:
This construct is useful for reversing an iterable
Notice that for negative steps the default
None (see http://stackoverflow.com/a/12521981 )
Python lists are 0-based i.e. the first element in the list can be accessed by the index
You can access the second element in the list by index
1, third element by index
2 and so on:
You can also use negative indices to access elements from the end of the list.
-1 will give you the last element of the list and index
-2 will give you the second-to-last element of the list:
If you try to access an index which is not present in the list, an
IndexError will be raised:
Indexing custom classes: __getitem__, __setitem__ and __delitem__
This allows slicing and indexing for element access:
While setting and deleting elements only allows for comma seperated integer indexing (no slicing):
Making a shallow copy of an array
A quick way to make a copy of an array (as opposed to assigning a variable with another reference to the original array) is:
Let's examine the syntax.
[:] means that
slice are all omitted. They default to
1, respectively, meaning that subarray that we are requesting will have all of the elements of
arr from the beginning until the very end.
In practice, this looks something like:
As you can see,
copy remained unchanged!
Note that this makes a shallow copy, and is identical to
Reversing an object
You can use slices to very easily reverse a
tuple (or basically any collection object that implements slicing with the step parameter). Here is an example of reversing a string, although this applies equally to the other types listed above:
Let's quickly look at the syntax.
[::-1] means that the slice should be from the beginning until the end of the string (because
end are omitted) and a step of
-1 means that it should move through the string in reverse.
Another neat feature using slices is slice assignment. Python allows you to assign new slices to replace old slices of a list in a single operation.
This means that if you have a list, you can replace multiple members in a single assignment:
The assignment shouldn't match in size as well, so if you wanted to replace an old slice with a new slice that is different in size, you could:
It's also possible to use the known slicing syntax to do things like replacing the entire list:
Or just the last two members:
Slices are objects in themselves and can be stored in variables with the built-in
slice() function. Slice variables can be used to make your code more readable and to promote reuse.