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.
More Related questions...