list.sort() — Python Technical Interview Questions & Answers

list.sort()

list.sort()

  • list.sort() works on a list. Lists can change. Many methods update the same list (append, pop, sort, insert) instead of returning a new one.
  • list.sort() — output: [70, 80, 90]. sort is in place. sorted() would return a new list.
  • Trap for list.sort(): append([1, 2]) nests a list. extend([1, 2]) adds 1 and 2. sort vs sorted is a viva favourite.
  index →  0       1       2
  list  → [Asha,  Ravi,  Neha]

Technical Interview Tip: In place or new list? Say it first, then one example.

Code Examples for list.sort()

Example

# list.sort()
a = [70, 90, 80]
a.sort()
print(a)

list.sort() — output: [70, 80, 90]. sort is in place. sorted() would return a new list.

How to Explain list.sort() to an Interviewer

Explain list.sort() as if you are teaching a junior — definition, then one tiny script.

list.sort() changes or reads a list. list.sort() — many list methods are in place.

What does the example print, and why?

list

What mistake do freshers make with list.sort()?

list.sort() — sort vs sorted, in place vs new list.