Computer Science
What are list slices? What for can you use them?
Python List Manipulation
39 Likes
Answer
List slice is an extracted part of the list containing the requested elements. The list slice is a list in itself. All list operations can be performed on a list slice. List slices are used to copy the required elements to a new list and to modify the required parts of the list. For example,
lst = [1, 2, 3, 4, 5]
lst2 = lst[1:4] #lst2 is [2, 3, 4]
#Using Slices for list modification
lst[0:2] = [10, 20] #lst becomes [10, 20, 3, 4, 5]
Answered By
18 Likes
Related Questions
Does the slice operator always produce a new list?
What's the purpose of the del operator and pop method? Try deleting a slice.
Compare lists with strings. How are they similar and how are they different?
What does each of the following expressions evaluate to? Suppose that L is the list
["These", ["are", "a", "few", "words"], "that", "we", "will", "use"].- L[1][0::2]
- "a" in L[1][0]
- L[:1] + L[1]
- L[2::2]
- L[2][2] in L[1]