Võ Quang Hòa
Võ Quang Hòa

Reputation: 3023

How to use filter function in python 33

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

Answers (3)

Pavan Tanniru
Pavan Tanniru

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

Martijn Pieters
Martijn Pieters

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

cdarke
cdarke

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

Related Questions