6.3 List Slicing

List Slicing

Similar to list indexing, you can use list slicing to get portions of a list
The general syntax is:
list_name[start:stop:step] # step is optional
For example:
my_list = [1, 2, "oh no", 4, 5.62] print(my_list[1:3]) # prints [2, "oh no"]
View code on GitHub.
Some tips for using this:
  • Step is how many indices you want to skip each time
  • The stop index is exclusive, so the element at the stop index is not included in the resulting list
  • A step of -1 means you're going in reverse order
  • list_name[:] gives you a full copy of the list
  • list_name[:stop] gives you everything up until the stop index (exclusive)
  • list_name[start:] gives you everything from the start index (inclusive) until the end of the list
You can also slice a list using negative indexes:
my_list = [1, 2, "oh no", 4, 5.62] print(my_list[-1:-3:-1]) # prints [5.62, 4]
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.