Skip to main content

Section 9.5 List slices

The slice operator also works on lists:
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list.
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']

Checkpoint 9.5.1.

    Q-2: 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.

Checkpoint 9.5.2.

    Q-3: What is printed by the following statements?
    alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
    print(alist[:])
    
  • []
  • An empty slice like this would not produce an empty list. Think about how the slice indexes.
  • [3]
  • This would be correct if the slice was [:1]
  • [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
  • Omitting both indexes in a slice will create a copy of the whole list.
Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle, or mutilate lists.
A slice operator on the left side of an assignment can update multiple elements:

Checkpoint 9.5.3.

    Q-5: What is printed by the following statements?
    L = [0.34, '6', 'SI106', 'Python', -2]
    print(len(L[1:-1]))
    
  • 2
  • The list begins with the second item of L and includes everything up to but not including the last item.
  • 3
  • Yes, there are 3 items in this slice.
  • 4
  • The list begins with the second item of L and includes everything up to but not including the last item.
  • 5
  • The list begins with the second item of L and includes everything up to but not including the last item.