Python Slices

Slices in Python can be used where only a portion of a string or list is required. This is particularly advantageous where a string or list is very large. When using slices, three optional values can be specified, a start position, a stop position and a step value. Below is an example of a slice that returns a portion of a string, where a start and stop value is specified in square brackets, separated by a colon.

stringexample = "This is a string"
print(stringexample[1:6])

A few things to note about slices are that, firstly, they are zero based, so the ‘T’ in the above example is at position zero and not one, and secondly, the portion extracted goes up to but not including the stop value. The above example would display the following.

his i

It isn’t absolutely necessary to specify both a start and stop value for the slice. Where no start value is specified, the slice starts from the first position in the string or list. Similarly, where no stop value is specified, the slice goes right to the end.

print(stringexample[:6])
print(stringexample[6:])

The first example above goes from the start of the string up to, but not including, a stop value of six, whilst the second example goes from a start value of six to the end of the string.

This i
s a string

If it is not required to return every value in a string or list, but instead, for example, return every other value, then the third optional step value can be included. Here, the above examples have been repeated, but with a step value of two to return every other character in the string.

print(stringexample[:6:2])
print(stringexample[6::2])

The resulting output is as follows.

Ti
sasrn

If every other value of the whole string is required in the output, this can be achieved by not specifying either a start or stop value.

print(stringexample[::2])

All of the techniques described so far will work with both strings and lists, however, with lists it is additionally possible to use slices to delete or replace parts of the list in question.

Replacing items in a list is accomplished in a similar fashion to assigning values to the list initially, except the slice values are specified in square brackets. Here the names ‘Fred’ and ‘Tom’ are replaced with ‘Frieda’, ‘John’ and ‘James’.

names = ["Andrew", "George", "Bob", "Fred", "Tom", "David"]
names[3:5] = ["Frieda", "John", "James"]

The full list now looks like this.

['Andrew', 'George', 'Bob', 'Frieda', 'John', 'James', 'David']

Deleting items in a list using a slice requires the ‘del’ function. The example below deletes the names ‘George’ and ‘Bob’ from the above list.

del names[1:3]