Python / Core Python Fundamentals Interview Questions
How does Python's sort work, and what is the difference between sort() and sorted()?
Python has two primary ways to sort: the list method list.sort() and the built-in function sorted(). Both use the Timsort algorithm (a hybrid of merge sort and insertion sort) with O(n log n) worst-case complexity, and both accept key= and reverse= arguments.
nums = [5, 2, 8, 1, 9]
# sort() — in-place, returns None, only on lists
nums.sort()
print(nums) # [1, 2, 5, 8, 9] — original modified
# sorted() — returns a new list, works on any iterable
original = (5, 2, 8, 1, 9) # tuple
result = sorted(original) # [1, 2, 5, 8, 9] — new list
print(original) # (5, 2, 8, 1, 9) — unchanged
# Sorting complex objects
products = [
{'name': 'Widget', 'price': 9.99, 'stock': 100},
{'name': 'Gadget', 'price': 4.99, 'stock': 250},
{'name': 'Doohickey', 'price': 14.99, 'stock': 30},
]
by_price = sorted(products, key=lambda p: p['price'])
by_stock_desc = sorted(products, key=lambda p: p['stock'], reverse=True)
# Multi-key sort: first by stock descending, then by name ascending
from operator import itemgetter
multi = sorted(products, key=lambda p: (-p['stock'], p['name']))Timsort is stable — equal elements preserve their original relative order. This property makes multi-key sorting straightforward: sort by secondary key first, then by primary key.
The operator.itemgetter and operator.attrgetter functions from the operator module are faster alternatives to lambdas for simple key extraction, especially in tight loops on large datasets.
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...
