Sequences (str, list, tuple) support indexing and slicing with start:stop:step. Slices return new objects—strings and tuples stay immutable; list slices are shallow copies of the slice range.
Indexing and slices
items = [0, 1, 2, 3, 4]
print(items[0], items[-1])
print(items[1:4]) # [1, 2, 3]
print(items[::2]) # every second
print("hello"[::-1]) # reverse
Slice assignment (lists only)
nums = [1, 2, 3, 4]
nums[1:3] = [20, 30]
print(nums)
Important interview questions and answers
- Q: Slice bounds?
A:stopis exclusive; out-of-range indices on slices clamp—unlike single indexing which raisesIndexError. - Q: [::-1] effect?
A: Reverses the sequence—works on strings without mutating them.
Self-check
- What does
[1:4]include from index 1? - How reverse a string without mutating?
Tip: Slice [start:stop:step]—stop is exclusive; negative indices count from the end.
Interview prep
- Slice stop exclusive?
a[1:4]includes indices 1,2,3—not 4—unlike some inclusive APIs in other languages.- Negative indices?
-1is last element; slices clamp out-of-range without IndexError.