Home > Back-end >  Why getting blank list after using filter and map function
Why getting blank list after using filter and map function

Time:12-30

#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))

CodePudding user response:

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]
  • Related