Skip to main content

Section 4.6 List Slices

The slice operation we saw with strings also work on lists. Remember that the first index is the starting point for the slice and the second number is one index past the end of the slice (up to but not including that element). Recall also that if you omit the first index (before the colon), the slice starts at the beginning of the sequence. If you omit the second index, the slice goes to the end of the sequence.
Check your understanding

Checkpoint 4.6.1.

    What is printed by the following statements?
    alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
    print(alist[4:])
    
  • [ [ ], 3.14, False]
  • Yes, the slice starts at index 4 and goes up to and including the last item.
  • [ [ ], 3.14]
  • By leaving out the upper bound on the slice, we go up to and including the last item.
  • [ [56, 57, "dog"], [ ], 3.14, False]
  • Index values start at 0.

Note 4.6.2.

Slices also take an optional third value, the step size. This specifies the rate at which the slice region increments (if the step size is positive) or the rate at which it decrements (if the step size is negative). It is also possible to specify -1 as the step term to slice with the values in reverse.

Checkpoint 4.6.3.

    What is printed by the following statements?
    alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
    print(alist[1:5:2])
    
  • [3, ’cat’]
  • Your indices are wrong. Remember that lists start at 0.
  • [67, [56, 57, ’dog’]]
  • Nice job!
  • [67, ’cat’, [56, 57, ’dog’], []]
  • Take note of the third value - the step size.

Checkpoint 4.6.4.

    What is printed by the following statements?
    alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
    print(alist[::-1])
    
  • [False, 3.14, [], [56, 57, ’dog’], ’cat’, 67, 3]
  • Correct! Everything is sliced backwards in this case.
  • [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
  • This is the original list!
  • False, 3.14, []
  • This operation is done on all of the items in the list, not just the first few.
You have attempted of activities on this page.