Sorting and Ordering

Sorting puts a collection in order. Both languages sort in place or return a new sorted collection, and both let you sort by a rule you define.

Sorting

PYTHON

nums = [5, 2, 9, 1]

print(sorted(nums))     # new list
nums.sort()             # in place
print(nums)

JAVASCRIPT

const nums = [5, 2, 9, 1];

console.log([...nums].sort((a, b) => a - b));
nums.sort((a, b) => a - b);
console.log(nums);
Compare → Python sorts numbers correctly by default. JavaScript's sort converts to text first, so [10, 9] sorts as [10, 9] unless you pass the comparison function (a, b) => a - b. This trips up experienced developers, always pass the comparator for numbers.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Sort a list of your own test scores from highest to lowest and print it, in both languages.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Sorting records by one of their fields is the version you will actually use.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Python names the sort key with a small inline function. JavaScript subtracts to decide order. Flip to ascending in both.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Nested Collections →
← Back