List Comprehension in Python

Level 370 keystrokes

This creates a list of squares using list comprehension, printing [1, 4, 9, 16, 25]. It's a concise way to transform lists.

Python code

# A list of the numbers 1 to 5
1nums = [1, 2, 3, 4, 5]
# List comprehension: computes x ** 2 for each x in nums
# The squares are collected into a new list; nums is unchanged
2squares = [x ** 2 for x in nums]
# Prints [1, 4, 9, 16, 25]
3print(squares)

Output

[1, 4, 9, 16, 25]
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.

  • ,× 4
  • [× 2
  • ]× 2
  • *× 2
  • =× 2
  • (× 1
  • )× 1

More Python examples at level 3

← Python typing practice