Register to get access to free programming courses with interactive exercises

Slices Python: Lists

You already know how to work with single elements. Now it's time to move on to a new tool. Python provides it for dealing with entire subsets of list items called slices.

The slice syntax

Slices are built into the language and have their syntax, so you can tell how widely used they are. They are written in the same way as references to list items by index are written:

some_list[START:STOP:STEP]

Slices have a total of three parameters:

  • START is the index of the first element
  • STOP is the index of the element before which the slice stops (this example does not include the STOP index)
  • STEP is the incremental step of the selected indexes

Mathematically speaking, the set will include the indices of the elements to be selected:

(START, START + STEP, START + 2 * STEP, .., STOP) # STOP does not enter the slice

For example, a slice of [3:20:5] means a sample of values with the indexes 3, 8, 13, and 18.

In this case, we can omit any of the three slice parameters and select a default value instead of the corresponding parameter:

  • Default START means from the beginning of the list
  • Default STOP means up to and including the end of the list
  • Default STEP means take every element

Here are some examples with different sets of parameters:

  • [:] / [::] are whole lists
  • [::2] are odd-numbered elements
  • [1::2] are even-numbered elements
  • [::-1] are all elements in reverse order
  • [5:] are all elements beginning with the sixth
  • [:5] are all elements up to but not including the sixth
  • [-2:1:-1] are all elements from the penultimate to third in reverse order. In all cases of selecting from a larger index to a smaller one, you need to specify the step/increment

Slices can work in two ways: selection and assignment.

Selecting items

Selections work with lists, tuples, and strings. The result of applying it is always a new value of the appropriate type:

'hello'[2:]  # 'llo'
(1, "foo", True, None)[2:]  # (True, None)
[1, 2, 3, 4, 5][2:]  # [3, 4, 5]

There are a few things that we need to mention about selecting straight away:

  • Tuples most often contain heterogeneous elements, so slicing is less useful for them than unpacking and repacking: it's hard to keep both element types and indexes in your head at the same time
  • Selecting by the slice [:] creates a new copy of the list, so this is how we usually copy the list
  • A slice generates a new list or tuple, but we copy only the link for each selected item

Assigning slices

Unlike strings and tuples, lists can change in place. One way of modifying them is by assigning a slice. We can do it using a list containing the corresponding number of new elements:

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

If you try to assign the wrong number of elements to a slice with a step, you'll get an error:

l = [1, 2, 3, 4]
l[::2] = [5, 6, 7]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: attempt to assign a sequence of size 3 to an extended slice of size 2

We have more freedom if the indices are consecutive and the slice is continuous, meaning its step is not specified. This slice can be assigned either more items (the list will grow) or less (it results in a truncated list):

l = [1, 2, 3]
l[2:] = [4, 5]
print(l)  # => [1, 2, 4, 5]
l[1:-1] = [100]
print(l)  # => [1, 100, 5]
l[:] = []
print(l)  # => []

First, the list grows, then it shrinks, and at the end, it becomes empty altogether — all with the help of the compact but powerful slice syntax.

Slices as values

In Python, we can create slices and use them as regular values.

We can construct a slice value using the slice() function:

first_two = slice(2)
each_odd = slice(None, None, 2)
print(each_odd)  # => slice(None, None, 2)
l = [1, 2, 3, 4, 5]
print(l[first_two])  # => [1, 2]
print(l[each_odd])  # => [1, 3, 5]

The slice() function takes between one and three parameters:

  • START
  • STOP
  • STEP

When we call a function with a parameter, we pass the STOP parameter to it.

If we want to skip one of the parameters, we substitute None. You can also use None in the bracketed slice entry — it means the same.

We can use any expression as a slice parameter if we compute it as an integer or None.

The START and STOP ratio

In the slice, the element with index STOP is not included in the sample, unlike the element with index START.

This behavior has one peculiarity. Whichever non-negative index n we choose, the equation given will be satisfied for any list:

l == l[:n] + l[n:]

Let's look at this example:

s = 'Hello!'
print(s[:2] + s[2:])  # => 'Hello!'
print(s[:4] + s[4:])  # => 'Hello!'
print(s[:0] + s[0:] == s)  # => True
print(s[:100] + s[100:] == s)  # => True

This property is convenient to use when parsing some text. You have to move the slice position of the string to the beginning and the remainder without worrying that any information on the slice boundary will be lost.


Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
new
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.