List slices in Python - 2 and 3 values forms, with an uplifting example
Archive - Originally posted on "The Horse's Mouth" - 2011-07-06 09:44:10 - Graham Ellis
Python's lists are indexed collection objects. That means that they're rather like arrays in that you look up elements by their position numbers, and the number start at a fixed point (0 in the case of Python); they're not totally like arrays in that they are not stored at unchanging sequential memory locations throughout the time they exist, so that you have additional flexibility in being able to extend them, insert elements into the middle, etc, at the expense of a slight loss of efficiency. The Python language and structure used also prevents you going out of bounds as you can (with disasterous consequences if you don't check) in languages such as C and C++.
Python also allows you to select slices from a list to create another list. This is a great way to get the "top ten" when you have sorted objects, or the last few, or something like that. Let's look at a list and some slices: elevator = [2,3,4,5,6,7,8,9,10,11,12,14,15]
print("The whole list")
print(elevator)
Where I am this week, there's a lift that runs from 2nd floor up to the 15th floor ... except that there is no 13th floor. So there are 13 floors in total, in list postion numbers 0 to 12. Printing out the whole list, as shown in the code above, gave: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15]
With list slices, I can sepcify a start point and a point before which I end - so: print(elevator[4:8])
will give me four positions - position numbers 4, 5, 6 and 7 which are floor numbers 6 to 8: [6, 7, 8, 9]
I can also specify start and end points that count down from the end (-1 being the last position, and so on), and I can leave out a position number entirely if I want to mean the very end of the list. Thus: print(elevator[:8])
print(elevator[4:])
print(elevator[4:-1])
Will give me: [2, 3, 4, 5, 6, 7, 8, 9]
[6, 7, 8, 9, 10, 11, 12, 14, 15]
[6, 7, 8, 9, 10, 11, 12, 14]
A further (two colons, up to 3 values) format of list slices alloes me to specify a step as well. Let's make one of our lift journeys into an express one, starting at the the floor in position number 3 in the list, stopping at every fourth floor thereafter, and nor reaching (stopping short of) the floor in position number 12 in the list. The code is: print(elevator[3:12:4])
and the result of running that code give the following journey: [5, 9, 14]
Again, I can leave out start and end points in the three value form; if I leave out the step it defaults to 1, which is the same as the two value format. Here are two final examples: print(elevator[3::3])
print(elevator[::2])
and here are the journeys that they cover: [5, 8, 11, 15]
[2, 4, 6, 8, 10, 12, 15]