Reputation: 3023
I'm now start learning python and I'm have problem with filter function.
If I run
list=list(range(10))
def f(x): return x % 2 != 0
print(((filter(f,list))))
I will get the result is
filter object at 0x00000000028B4E10
Process finished with exit code 0
And if I modify the code to
list=list(range(10))
def f(x): return x % 2 != 0
print(list(filter(f,list)))
The result I get will be
Traceback (most recent call last):
File "C:/Users/Vo Quang Hoa/PycharmProjects/HelloWorld/Hello.py", line 6, in <module>
print(list(filter(f,list)))
TypeError: 'list' object is not callable
Process finished with exit code 1
What's happend. How to get the list 1 3 5 7 9 Thank for your help.
Upvotes: 1
Views: 5682
Reputation: 321
I hope this help to you
ran=range(10)
def f(x): return x % 2 != 0
res = filter(f,ran)
for i in res:
print(i,end=' ')
Upvotes: 0
Reputation: 1125058
You renamed list
, giving it a different value. Don't do that, you shadowed the built-in type. Change your code to use a different name instead:
some_list = list(range(10))
def f(x): return x % 2 != 0
print(list(filter(f, some_list)))
and then filter()
works just fine.
Upvotes: 3
Reputation: 44434
Your main problem is that you called your list
variable, um, list
. You must not use the same name as other objects! Call your list something else, and/or use a naming convention like upper camel case;
Fred=list(range(10))
def f(x): return x % 2 != 0
print(list(filter(f,Fred)))
Upvotes: 2