Shahbaj
Shahbaj

Reputation: 3

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

Upvotes: 0

Views: 148

Answers (1)

user7864386
user7864386

Reputation:

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]

Upvotes: 3

Related Questions