ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
print(sorted([-2, 1, 2, -1], key=abs))
  1. A. [-1, 1, 3, -2]
  2. B. [1, -1, 2, -3]
  3. C. [1, -1, -2, 2]
  4. D. [-2, 1, 2, -1]

Correct answer: C. [1, -1, -2, 2]

Sorting by absolute value keeps equal keys in input order. Among the values with absolute value 1, 1 comes before -1, and among those with absolute value 2, -2 comes before 2.

More Python Programming questions

Exams that ask this topic