It is often the case that a program requires referencing a group of elements within a list (instead of a single element using a single value of the index). This can be accomplished by slicing. Consider running this example:
x=[101,-45,34,-300,8,9,-3,22,5] print() print(x) print(x[0:9])
The colon operator can be used to index multiple elements with the list. The index on the left side of the colon (:) is the starting index. By Python's indexing convention, the value on the right side of the colon (:) indexes that value minus one (be careful with the right index). Since the variable
x has 9 elements indexed from 0 to 8,
x[0:9] references all indices from 0 to 8. Here are some more examples you should try:
print() print(x[3:4]) print(x[3:5]) print(x[3:6]) print(x[3:7]) print(x[3:8]) print(x[3:9])
Again, you should be careful when using the right index since Python will sequence up to that value minus one. For the sake of convenience, there are also shorthand slicing techniques that do not require specifying the start or ending index when it assumed the complete rest of the list is being referenced:
print() print(x[3:]) print(x[:4])
In addition to specifying the start and stop indices, you can also specify the "step". Here is an example that will count by twos from element 3 to element 7 (every other element starting at index 3). The step size is given by the index value after the second colon.
Finally, Python allows for negative indices where, by convention, the index -1 implies starting from the end of the list.
print() print(x[-1]) print(x[-1:-3:-1]) print(x[-1:-len(x)-1:-1])
In these examples, the step size of -1 means to count backwards in steps of -1.
This video reviews many of the list concepts we have discussed so far. At 6:11, it discusses and elaborates on the rules for slicing in Python. Be sure to follow along and practice the examples in Repl.it.