A Python slice extracts elements, based on a start and stop. We specify an optional first index, an optional last index, and an optional step.
Understanding slice syntax in Python is important. It allows us not just to slice arrays, but also take substrings. This can be used in many programs.
List
This program takes a slice of a list. We first create a list with five numeric elements. We specify in the slice two values: 1 and 3. At index 1, we have the value 200.
values = [100, 200, 300, 400, 500] # Get elements from second index to third index. slice = values[1:3] print(slice)[200, 300]
The second index in slice notation may be negative. This means counting begins from the last index. So a negative one means the same as "length minus one."
values = [100, 200, 300, 400, 500] # Slice from third index to index one from last. slice = values[2:-1] print(slice)[300, 400]
In slicing, if you omit the first or second index, it means "start" or "end." This is clearer than specifying 0 or the length.
values = [100, 200, 300, 400, 500] # Slice from start to second index. slice = values[:2] print(slice) # Slice from second index to end. slice = values[2:] print(slice)[100, 200] [300, 400, 500]
We use the slice notation on strings. In this example, we omit the first index to start at the beginning, and then consume four characters total. We extract the first four letters.
word = "something" # Get first four characters. part = word[:4] print(part)some
There is a third, optional index used in slicing: the step. If the step is two, we advance two places after an element is copied. So we can skip over elements.
values = "AaBbCcDdEe" # Starting at 0 and continuing until end, take every other char. evens = values[::2] print(evens)ABCDE
Slicing is safe. It will cause no errors assuming you use integers as arguments. Often when programming, a tiny error will cause an extreme disaster and the program will implode.
values = [9, 8, 7, 6] # This causes no error. test = values[555:555:5555] print(test)
TypeError
Arguments to slice must be of a valid type. They cannot be strings or collections. If an object has an __index__ method, it can be used in place of an integer as a slice index.
values = ["carrot", "rat"] # Must use indexes or None. test = values["friend":"dog"] print(test)Traceback (most recent call last): File "...", line 7, in <module> test = values["friend":"dog"] TypeError: slice indices must be integers or None or have an __index__ method
There is a slice built-in method. It returns a slice object. As the documentation states, slice objects are not used in core types, but are sometimes needed in numerical libraries.
string
, list or other built-in type, pay no attention to the slice method. It won't help you.# Create a slice object. example = slice(1, 10, 0) print(example.start, example.stop, example.step)1 10 0
The special syntax for this operation is at first confusing. But with practice, slicing becomes easy. When we omit a value, a default is used.
Get elements from... values[1:3] Index 1 through index 3. values[2:-1] Index 2 through index one from last. values[:2] Start through index 2. values[2:] Index 2 through end. values[::2] Start through end, skipping ahead 2 places each time.
A slice can be used to resize a list. We can remove elements past a certain length. This makes the list smaller (reduces its size). We can also pad a list with new elements.
Tuple
Tuples too may be sliced. Slicing notation is standardized throughout Python 3 objects. So once you learn it on lists or strings, you can slice tuples without much trouble.
Slices are used throughout Python programs—we take substrings, copy lists and resize lists. This syntax is versatile. It provides useful defaults when values are omitted.