You already know how to work with single elements. Now it's time to move on to a new tool. Python provides it for dealing with entire subsets of list items called slices.
The slice syntax
Slices are built into the language and have their syntax, so you can tell how widely used they are. They are written in the same way as references to list items by index are written:
some_list[START:STOP:STEP]
Slices have a total of three parameters:
START
is the index of the first elementSTOP
is the index of the element before which the slice stops (this example does not include theSTOP
index)STEP
is the incremental step of the selected indexes
Mathematically speaking, the set will include the indices of the elements to be selected:
(START, START + STEP, START + 2 * STEP, .., STOP) # STOP does not enter the slice
For example, a slice of [3:20:5]
means a sample of values with the indexes 3, 8, 13, and 18.
In this case, we can omit any of the three slice parameters and select a default value instead of the corresponding parameter:
- Default
START
means from the beginning of the list - Default
STOP
means up to and including the end of the list - Default
STEP
means take every element
Here are some examples with different sets of parameters:
[:]
/[::]
are whole lists[::2]
are odd-numbered elements[1::2]
are even-numbered elements[::-1]
are all elements in reverse order[5:]
are all elements beginning with the sixth[:5]
are all elements up to but not including the sixth[-2:1:-1]
are all elements from the penultimate to third in reverse order. In all cases of selecting from a larger index to a smaller one, you need to specify the step/increment
Slices can work in two ways: selection and assignment.
Selecting items
Selections work with lists, tuples, and strings. The result of applying it is always a new value of the appropriate type: