Why is the list I print not filtered?


#1

Question

Why is the list I print not filtered?

Answer

If you’ve written your filter() code on a line by itself, it will not be printed to the screen. The only way something will be printed is to use the print function.
It’s perfectly fine to print the results of a function by writing that function, like filter() after the word print, like this:
print filter(lambda, list_name)


FAQ: Learn Python - Advanced Topics in Python - Try It!
#2

a=[x*2 for x in range(1,11)]
print(filter(lambda x: x<8,a))
when I run this code in command promt , it return:
<filter object at 0x000000000294E588>
why?
I’m using python -3


#3

Cause python3 is dumb about this stuff, and print() used on objects tries to call __repr__ or __str__ , which they probably don’t have.
Do print(list(lambda x: x<8, a)) since print() can figure out how to print out a list

Edit:
I looked more into it. Basically, its not that python3 is dumb. They intentionally don’t really want you to use filter() and map() to get a list. They recommend using list comprehensions instead now. If you want to still use it this way, you have to manually use list() to turn it into a list.


#4

The decision was made on purpose to use an iterator for things like filter, which is more memory efficient:

https://stackoverflow.com/questions/25653996/what-is-the-difference-between-list-and-iterator-in-python