Python language basics 44: slicing a list
September 5, 2015 Leave a comment
Introduction
In the previous post we looked at the index function for collections. We saw how it helped find the location of an object by returning the position as an integer.
In this post we’ll look at how to slice a list.
Slicing
You probably know the English word ‘slice’, e.g. a slice of bread. Slicing a collection is similar. In the case of a collection slicing means extracting a subset of the collection into another one.
Consider the following collection of cities:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"]
Say you’d like to extract all elements from position 1 – i.e. the second element “Budapest” – to and including the position 4, i.e. “Birmingham”. Slicing is an indexer-based operation, i.e. there’s no “slice” method or similar. The start index is inclusive and the end index is exclusive which is called a half-open range. The indexes are separated by a colon ‘:’.
Hence the solution looks as follows:
reduced = cities[1:5]
‘reduced’ will look as follows:
[‘Budapest’, ‘Berlin’, ‘Paris’, ‘Birmingham’]
It’s OK to ignore either the start or the end index. The following will extract all elements starting from position 3:
reduced = cities[3:]
[‘Paris’, ‘Birmingham’, ‘Zürich’]
Whereas the following code extract everything from the start up until position 3:
reduced = cities[:3]
[‘Stockholm’, ‘Budapest’, ‘Berlin’]
Slicing can be used to to copy a list which we’ll look at in the next post among other techniques for creating copies.
Read all Python-related posts on this blog here.