Sorted with Key in Python

Level 380 keystrokes

This sorts words by length, printing ['pie', 'apple', 'banana']. The key parameter determines the sorting criteria.

Python code

# Three words of different lengths
1words = ["apple", "pie", "banana"]
# sorted() returns a new list; key=len compares the lengths
# "pie"(3) < "apple"(5) < "banana"(6)
2result = sorted(words, key=len)
# Prints ['pie', 'apple', 'banana']
3print(result)

Output

['pie', 'apple', 'banana']
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 6
  • ,× 3
  • =× 3
  • (× 2
  • )× 2
  • [× 1
  • ]× 1

More Python examples at level 3

← Python typing practice