Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter object error in Python 3

When I run this code in Python 3:

languages = ["HTML", "JavaScript", "Python", "Ruby"]
print( filter(lambda x: x == "Python",languages))

I get this error:

filter object at 0x7fd83ff0
filter object at 0x7feede10

I do not know what the error means - and it runs ok in Python 2.7.

Can anyone suggestion a solution?

like image 913
Jose Maria Avatar asked Mar 17 '17 20:03

Jose Maria


1 Answers

It is not an error - you printed an object of type filter as the filter() don't return list - it constructs an iterator, but only if there is a request for it.

The simplest solution is to use the function list() - it requests an iterator and returns the list:

print( list(filter(lambda x: x == "Python", languages)))

instead of your command

print( filter(lambda x: x == "Python",languages))

Note: It is similar to printing range(10) (which is an object) and printing list(range(10)) (which is the list).

There are changes between Python 2.x and Python 3.x in almost all functions which returned a list in Python 2.x - in Python 3.x they return something more general and less memory consuming, something as recipe how to obtain elements in the case of interest.

Compare: 1, 2, 3, 4, 5, 6, 7, 8, 9 and integers from 1 to 9 (or 1, 2, ..., 9).
No difference? Try write down all integers from 1 to 999999.

like image 143
MarianD Avatar answered Oct 02 '22 16:10

MarianD