Back to Practice
#0148

Take First N Items From an Iterable

MediumPython25 min20 XP

Problem

Given any iterable and n, return a list containing at most the first n values.

Why This Matters

Streaming pipelines and generators should not be converted into full lists when you only need a small prefix.

Function Signature

def take(iterable, n):

Examples

Example 1
Input(x*x for x in range(10)), n = 4
Output[0, 1, 4, 9]

Only four generated values are consumed.

Constraints

  • Return the exact requested value.
  • Handle empty or small inputs when the prompt allows them.
  • Keep the code readable and deterministic.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Input(x*x for x in range(10)), n = 4
Expected[0, 1, 4, 9]

Only four generated values are consumed.

Hidden Test Categories
empty or smallest inputduplicates or repeated valueslarger realistic input