🐍 Python Beginner

What is Python's sorted() vs list.sort()?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Python topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

Both sort iterables but differ in important ways. sorted(iterable, key=None, reverse=False) is a built-in function that returns a new sorted list from any iterable (list, tuple, string, dict). The original is unchanged. list.sort(key=None, reverse=False) is a list method that sorts in-place and returns None. It only works on lists. The key parameter is a function applied to each element before comparison: sorted(words, key=str.lower), sorted(people, key=lambda p: p["age"]). Use operator.itemgetter or attrgetter for faster key extraction. Both use Timsort — a stable sort algorithm (O(n log n), preserves relative order of equal elements). Stability is important for multi-level sorting: sort by name first, then by age.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Python answers easy to follow.