Geni Allaine
Geni Allaine

Reputation: 45

How can I rewrite this function with list comprehension?

I want to use a list comprehension to call this function.

def perfect_squares(limit):
    value = 1
    while value < limit:
        yield value*value
        value += 1

foo = perfect_squares(1000)
for i in range(6):
    print(next(foo))

Upvotes: 0

Views: 193

Answers (2)

Jab
Jab

Reputation: 27485

I believe you’re looking for a comprehension so the function still is a generator

def perfect_squares(limit):
    yield from (v*v for v in range(1,limit))

Or as returning a actual list using a list comprehension:

def perfect_squares(limit):
    return [v*v for v in range(1,limit)]

Upvotes: 3

Vishal
Vishal

Reputation: 3296

Since you are using yield, you cannnot do this with list comprehension. If you want to use list comprehension, you should produce the whole list first, and then print them instead.

Without yield, you can do it as follows:

power_of_2 = [x ** 2 for x in range(1, 1000)] 

Upvotes: 2

Related Questions