Skip to content
On this page

Slicing

Extracting a portion of elements from a list or tuple is a common operation. For example, consider the following list:

python
>>> L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']

How can we get the first three elements?

A naive approach would be:

python
>>> [L[0], L[1], L[2]]
['Michael', 'Sarah', 'Tracy']

This is considered a naive method because it becomes cumbersome when trying to extract the first ( N ) elements.

To get the first ( N ) elements, which are the elements with indices from 0 to ( N-1 ), we can use a loop:

python
>>> r = []
>>> n = 3
>>> for i in range(n):
...     r.append(L[i])
... 
>>> r
['Michael', 'Sarah', 'Tracy']

Using a loop for this kind of operation is quite tedious, so Python provides a slicing operator, which greatly simplifies this task.

For the above example, to get the first three elements, you can complete the slicing in one line of code:

python
>>> L[0:3]
['Michael', 'Sarah', 'Tracy']

L[0:3] means to extract elements starting from index 0 up to, but not including, index 3, which corresponds to indices 0, 1, and 2—exactly three elements.

If the first index is 0, it can be omitted:

python
>>> L[:3]
['Michael', 'Sarah', 'Tracy']

You can also start from index 1 and extract two elements:

python
>>> L[1:3]
['Sarah', 'Tracy']

Similarly, since Python supports L[-1] to get the last element, it also supports negative slicing. Let's try:

python
>>> L[-2:]
['Bob', 'Jack']
>>> L[-2:-1]
['Bob']

Remember that the index of the last element is -1.

Slicing operations are very useful. First, let's create a sequence of numbers from 0 to 99:

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

You can easily extract a portion of this sequence using slicing. For example, the first 10 numbers:

python
>>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The last 10 numbers:

python
>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

The numbers from index 11 to 20:

python
>>> L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

The first 10 numbers, taking every second number:

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

All numbers, taking every fifth number:

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

You can even copy the list as is by writing [:]:

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

A tuple is also a kind of list, with the only difference being that a tuple is immutable. Therefore, slicing operations can also be applied to tuples, though the result will still be a tuple:

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

The string 'xxx' can also be considered a kind of list, where each element is a character. Therefore, strings can also use slicing operations, with the result still being a string:

python
>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'

In many programming languages, there are various substring functions provided for strings (e.g., substring), which essentially serve the purpose of string slicing. Python does not have separate substring functions; slicing is all that is needed, making it very simple.

Exercise

Using the slicing operation, implement a trim() function that removes leading and trailing whitespace from a string, ensuring not to call the str.strip() method:

python
def trim(s):
    return s

Test Cases:

python
# Tests:
if trim('hello  ') != 'hello':
    print('Test failed!')
elif trim('  hello') != 'hello':
    print('Test failed!')
elif trim('  hello  ') != 'hello':
    print('Test failed!')
elif trim('  hello  world  ') != 'hello  world':
    print('Test failed!')
elif trim('') != '':
    print('Test failed!')
elif trim('    ') != '':
    print('Test failed!')
else:
    print('Test succeeded!')

Summary

With slicing operations, many loops become unnecessary. Python's slicing is highly flexible, allowing many operations that would require multiple lines of loop code to be accomplished in a single line.

Slicing has loaded