Filter

Create a list, squares , that consists of the squares of the numbers 1 to 10. A list comprehension could be useful here!

Use filter() and a lambda expression to print out only the squares that are between 30 and 70 (inclusive).

my code was:

squares = [x**2 for x in range(1,11)]
for square in squares:
print (filter(lambda square : square in range (30,71) ,squares))

but the answer was simply just:
squares = [x**2 for x in range(1,11)]
print filter(lambda x : x in range (30,71) ,squares)

i dont understand that the indexes in SQUARES are x**2 in range(1,11), but x is not. so w do we filter out x instead of defining indexes in SQUARES and filter out?

@yushan6714638042, the for-in expression is included in the filter() function.

filter(f, y) where f is a boolean function (returns True or False) and y is an iterable, says: for every element in the iterable y, apply the boolean function f and then return a new iterable containing those values from y for which f returned True.

1 Like