Python / Core Python Fundamentals Interview Questions
How does slicing work in Python for lists, strings, and tuples?
Slicing extracts a sub-sequence from any sequence type using the notation sequence[start:stop:step]. All three parts are optional and default to the beginning, end, and a step of 1 respectively. Slicing always returns a new object of the same type — it does not modify the original.
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] data[2:5] # [2, 3, 4] â stop is exclusive data[:4] # [0, 1, 2, 3] â from beginning data[6:] # [6, 7, 8, 9] â to end data[::2] # [0, 2, 4, 6, 8] â every other element data[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] â reverse data[-3:] # [7, 8, 9] â last three elements data[1:8:3] # [1, 4, 7] â start=1, stop=8, step=3
Strings and tuples behave identically. text = 'Hello, World!'; text[7:] gives 'World!'. The [::-1] idiom is the classic one-liner to reverse a string in Python.
Slicing on lists returns a shallow copy. Assigning to a slice mutates the list in-place, which is a powerful but occasionally surprising feature:
data[2:5] = [20, 30] # replace three elements with two print(data) # [0, 1, 20, 30, 5, 6, 7, 8, 9] â length changed
For more reusable slice objects, slice(start, stop, step) creates a first-class slice that can be stored and reused: s = slice(1, 8, 2); data[s].
More Related questions...