All sample questions / Python

Python Lists, Tuples and Slicing, what does print(b) print after a = [3, 1, 2]?

Block 4, Lists, Tuples and Slicing, question 2 of the Python sample

a = [3, 1, 2]
b = a.sort()
print(b)

What does this print?

  1. A. None
  2. B. [1, 2, 3]
  3. C. [3, 1, 2]
  4. D. True
Show the answer and why each option is right or wrong

Answer, A. None

A. None
Correct. list.sort() sorts the list in place and returns None, so b ends up holding None regardless of how a itself changed.
B. [1, 2, 3]
Assumes sort() returns the sorted list, the way sorted() does, instead of mutating in place and returning nothing.
C. [3, 1, 2]
Assumes sort() returns a reference to the list before it was sorted.
D. True
Assumes an in place mutating method reports success as a boolean rather than returning None.

Methods that mutate a list in place, such as sort, reverse, append and extend, consistently return None so that their result is never mistaken for a new object. To get the sorted list itself, the value has to be read from the variable that was sorted, not from the method call.

The answer above is what the CPython interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 Python interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 Python questions, 9 euros

Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros

Or play the free Python sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.