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