List and String Slicing
January 6, 2018
List and String Slicing
Python provides a helpful utility called slicing that enables us to easily subset a list. Slicing can also be applied to other iterables, such as tuples or strings.
Basic Slicing
Let’s create a list of 5 people.
people = ['amy', 'barry', 'cory', 'diane', 'elaine']
We can select the first and second person in the list without using a for
loop by slicing it.
Note 1: Python is zero-indexed, therefore we are looking at the 0th and 1st element in the list.
Note 2: Slicing includes the start index, up to but not including the end index.
print(people[0:2])
['amy', 'barry']
It is also possible to subset the whole list (seems strange for now, but I promise there’s a valid use case for this).
print(people[::])
['amy', 'barry', 'cory', 'diane', 'elaine']
A very useful function of slicing is that it allows us to reverse the order of a list.
print(people[::-1])
['elaine', 'diane', 'cory', 'barry', 'amy']
Slicing by Increments
The third parameter allows us to define the “step”, which allows us to set how the list’s index will increment. This is by default set to 1 (no values are skipped). The code below slices the entire list, and keeps items that are 2 indexes away from each other.
numbers = [1, 2, 3, 4, 5]
print(numbers[::2])
[1, 3, 5]
String Slicing
Slicing can also be applied to strings - simply think of a string as a list of characters.
string = 'The quick brown fox jumps over the lazy dog.'
print(string[0:3])
The
Python allows us to easily reverse a string using the following syntax.
print(string[::-1])
.god yzal eht revo spmuj xof nworb kciuq ehT
This is admittedly not the most useful function that we can apply to a string, but nonetheless we do have the ability to create a new string that skips by a specified number of characters.
print(string[::2])
Teqikbonfxjmsoe h aydg