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=3Strings 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 changedFor 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].
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
