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']
- [ [ ], 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.
Q-2: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[4:])
- []
- 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.
Q-3: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[:])
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:
- 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.
Q-5: What is printed by the following statements?
L = [0.34, '6', 'SI106', 'Python', -2]
print(len(L[1:-1]))
You have attempted of activities on this page