Filter with Lambda in Python

Level 387 keystrokes

This filters the list to keep only even numbers, printing [2, 4, 6]. Lambda is an anonymous function for quick operations.

Python code

# A list of the numbers 1 to 6
1nums = [1, 2, 3, 4, 5, 6]
# filter() keeps the items for which the lambda returns True (x % 2 == 0: even)
# filter() is lazy, so list() collects the result: [2, 4, 6]
2evens = list(filter(lambda x: x % 2 == 0, nums))
# Prints [2, 4, 6]
3print(evens)

Output

[2, 4, 6]
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
  • =× 4
  • (× 3
  • )× 3
  • :× 1
  • [× 1
  • ]× 1
  • %× 1

More Python examples at level 3

← Python typing practice