Junior — Middle
Can you explain what slices are in Python and how they are used for working with lists and strings?
sobes.tech AI
Answer from AI
Slices in Python are a way to obtain a part of a sequence (list, string, tuple) by index, specifying the start, end, and step. Slices allow easy extraction of sublists or substrings without modifying the original object.
Slice syntax:
sequence[start:stop:step]
start— the starting index of the slice (inclusive), default is 0stop— the ending index of the slice (exclusive), default is the length of the sequencestep— the step, default is 1
Examples:
lst = [0, 1, 2, 3, 4, 5]
print(lst[1:4]) # [1, 2, 3]
print(lst[:3]) # [0, 1, 2]
print(lst[::2]) # [0, 2, 4]
print(lst[::-1]) # [5, 4, 3, 2, 1, 0] - reverse of the list
s = "hello"
print(s[1:4]) # 'ell'
print(s[::-1]) # 'olleh'
Slices do not modify the original object but create a new object with the selected elements. This is useful for data processing and analysis, copying parts of lists and strings.