How to use filter function in python 33

Question:

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.

Asked By: Võ Quang Hòa

||

Answers:

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.

Answered By: Martijn Pieters

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)))
Answered By: cdarke

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=' ')
Answered By: Pavan Tanniru
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.