Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why getting blank list after using filter and map function

#Program to map and filter to make a list whose elements are cubes of even numbers

#function for even number to use in filter

def even(num):
  if num%2==0:
    return num

def cube(num):
  return num**3   

a=range(1,10)
print(list(a))
b=filter(even,a)
print(list(b))
c=map(cube,b)
print(list(c))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

b is a generator. When you cast it to list using list() constructor, it is exhausted. If you comment out the following line:

print(list(b))

your code will work as intended.

As a side note, you can write all this in one line:

list(map(lambda x: x**3, filter(lambda x: x%2==0, a)))

(but I think you knew this already).

Output:

[8, 64, 216, 512]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading