16.Comprehending Comprehensions/filter


#1

When I enter this:

threes_and_fives= [x for x in range(1,16)]

print filter(lambda x:(x%3)==0 or (x%5)==0, threes_and_fives)

I get this output:

[3, 5, 6, 9, 10, 12, 15]
None

and an error code: "Oops, try again.
threes_and_fives contains 1, but shouldn't."

When I enter this however:

threes_and_fives= [x for x in range(1,16) if (x%3)==0 or (x%5)==0]

print threes_and_fives

i get this output and no error message:

[3, 5, 6, 9, 10, 12, 15]

None

Why cant i use a filter? The result is exactly the same right?

`


#2

You can use filter, but you should still assign the result to threes_and_fives. You can't do this immediately though. filter returns something called a generator. A generator generates your full answer, one piece at a time. With filter, it returns one element of the list that satisfies the condition at a time.

One other aspect of a generator, is that it's lazy. If it doesn't really need to do something, it won't. So if you don't loop over the generator, it doesn't return anything. If you want all the results of a generator in a list, you can surround the filter function with list, like this:

print list(filter(f, l))