Skip to main content
Contents Index
Search Book
Search Results:
No results.
Readability settings Prev Up Next Scratch ActiveCode Profile
title here
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
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']
Activity 9.5.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.
Activity 9.5.2 .
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:
Activity 9.5.3 .
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.
You have attempted
of
activities on this page.