Skip to main content

Section 28.4 Slicing a List

Now that we know how to iterate through parts of a list, we could use that technique to copy just part of a list. Say we have a list with the 12 months, and from it, we want to copy out just the summer months (June-August). We know those are months 6-8 (human numbering), which means in computer counting, they will be indexes 5-7. That means we need to use range(5, 8, 1) to loop through them. As we access each one, we will append it to the summerMonths list that starts empty.
But, rather than do that work ourselves, there is syntax in Python for asking for part of a list. Part of a list is known as a slice. We ask for a slice in a similar way we ask for a single item. To get a single item from a list, say the item at index 4, we say list[4]. To ask for a slice of list we would say something like: list[4:10] which says “I want a copy of items number 4 through 9”. Notice that the second value, which is the stopping point, is not included in the slice.
That means a much easier way to get a list of the summer months would be:

Note 28.4.1.

Remember that the slice always stops just before the second index. [5:8] only slices indexes 5-7.
There are some handy shortcuts we can use when specifying a slice. If you don’t give a second index, like [5:], it means “to the end of the list”. If you use a negative value, it is counted from the end of the list. [-3:-1] means “the slice from the third to the last item up to but not including the last item”. [-2:] would mean “the last two items”.

Checkpoint 28.4.2.

    Check all the valid ways to specify the slice that includes “Sep”, “Oct”, “Nov”, “Dec”
  • [9:]
  • Index 9 is for the 10th item, which is "Oct".
  • [8:12]
  • Correct.
  • [-4:]
  • Correct.
  • [-4:-1]
  • -1 as the stop value will stop before the last item.

Warning 28.4.3.

If the end index you give in the slice is less than the start one, like [5:2], you will always get an empty list as a result. Same if you specify a starting index past the end of the list by doing something like months[15:].
You have attempted of activities on this page.