Why should you use sorted() instead of list.sort() when sorting a list of dictionaries in Python?
💡 Model Answer
In Python, sorted() and list.sort() both sort sequences, but they differ in how they operate and when you should use each. sorted() is a built‑in function that accepts any iterable and returns a new list containing the sorted items. It does not modify the original sequence, making it safe to use when you need to preserve the original order. list.sort() is a method that mutates the list in place, returning None. It can only be called on list objects, not on other iterables. Because sorted() creates a new list, it uses more memory but allows you to keep the original list unchanged. list.sort() is slightly faster for large lists because it avoids the overhead of allocating a new list. sorted() also accepts any iterable, so you can sort tuples, generators, or custom objects directly. In practice, use sorted() when you need a sorted copy or when working with non‑list iterables. Use list.sort() when you want to sort the list in place and you don't need the original order, especially in performance‑critical code. Both functions are stable, meaning equal elements retain their relative order.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500