Python Slice Example

1. Slice List.

Taking a partial element from a list or tuple is a very common operation. For example, how to take the first three elements from below list?

>>> L = ['Richard', 'Tom', 'Jerry', 'Jackie', 'Kevin']

You can take elements from above list like below.

>>> [L[0], L[1], L[2]]
['Richard', 'Tom', 'Jerry']

But when you want to take the first N elements from above list, you should use below code.

>>> r = []
>>> n = 3
>>> for i in range(n):
...     r.append(L[i])
>>> r
['Richard', 'Tom', 'Jerry']

For such operations, which often take a specified index range, the use of loops is cumbersome, so Python provides Slice operators that greatly simplify this operation. Corresponding to the above problem, the first three elements can be sliced in one line of code.

>>> L[0:3]
['Richard', 'Tom', 'Jerry']

L [0:3] indicates that the index is taken from 0 until index 3, but not include index 3. So the elements at index 0, 1, 2 will be extract from above list. If the first index is 0, you can omit it like below.

>>> L[:3]
['Richard', 'Tom', 'Jerry']

You can also start at index 1 and pull out two elements.

>>> L[1:3]
['Tom', 'Jerry']

Similarly, since Python supports L[-1] to take the last element, it also supports reciprocal slicing like below. Remember that the index of the penultimate first element is -1

# take the last two elements from list.
>>> L[-2:]
['Jackie', 'Kevin']
# take the penultimate element from list.
>>> L[-2:-1]
['Jackie']

Slicing is very useful. Let’s first create a sequence of 0-99:

>>> L = list(range(100))
>>> L
[0, 1, 2, 3, ..., 99]

It is easy to extract a sequence of numbers by slicing. For example, the top 10 numbers and the later 10 numbers.

>>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

The first 10 numbers, you take one for every two.

>>> L[:10:2]
[0, 2, 4, 6, 8]

In all of the numbers, you take one for every five.

>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

Even if you don’t write anything, you can just write [:] to copy a list.

>>> L[:]
[0, 1, 2, 3, ..., 99]

2. Slice Tuple.

A tuple is also a list, except that a tuple is immutable. So, a tuple can also be sliced, but the result is still a tuple.

>>> l = (0, 1, 2, 3, 4, 5)
>>> l[:3]
(0, 1, 2)

3. Slice String.

In many programming languages, there are many interception functions (substring, for example) for strings, whose purpose is to slice strings. Python has no interception function for strings. It only needs one slice operation to complete, which is very simple.

The string ‘XXX’ can also be thought of as a list, where each element is a character. Therefore, strings can also be sliced, but the result is still a string.

>>> 'code-learner.com'[:3]
'cod'
>>> 'code-learner.com'[::2]
'cd-ere.o'