Generator Expression Pipeline in Python

Level 5238 keystrokes

This chains generator expressions to create a lazy evaluation pipeline for data transformation.

Python code

# Define function that processes data through pipeline
1def process_pipeline(data):
# Stage 1: keep only positive numbers (lazy: nothing runs yet)
2 positives = (x for x in data if x > 0)
# Stage 2: square each positive number
3 squared = (x ** 2 for x in positives)
# Stage 3: keep only squares below 100
4 result = (x for x in squared if x < 100)
# list() pulls the values through all stages and returns them
5 return list(result)
6
# Test data with mixed positive and negative numbers
7numbers = [-5, 3, -2, 8, 12, 1, -7, 6]
# Process and print: [9, 64, 1, 36] (positive → squared → <100)
8print(process_pipeline(numbers))

Output

[9, 64, 1, 36]
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.

  • ,× 7
  • (× 7
  • )× 7
  • =× 4
  • -× 3
  • _× 2
  • *× 2
  • :× 1
  • [× 1
  • ]× 1

More Python examples at level 5

← Python typing practice