Write a function that returns the squares of every integer from 1 to n, using a list comprehension (not a for loop with .append()).
squares_up_to(n)
squares_up_to(5) // → [1, 4, 9, 16, 25]
squares_up_to(1) // → [1]
squares_up_to(3) // → [1, 4, 9]
def squares_up_to(n):
return [i * i for i in range(1, n + 1)]
This is a direct application of the list comprehension syntax from the lesson: [expression for variable in iterable]. The expression is i * i (the square), and the iterable is range(1, n + 1) — the same off-by-one adjustment from Sum To N to make sure n itself is included, since range(start, stop) always stops before stop.
Compare it to the loop version, which does exactly the same work with more ceremony:
def squares_up_to(n):
result = []
for i in range(1, n + 1):
result.append(i * i)
return result
Both produce identical output — the comprehension just says the same thing in one line instead of four, once the pattern is familiar.
def squares_up_to(n):
return [i * i for i in range(1, n + 1)]
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.