3

Why I am geting a wrong list when I use the function map() in python? here is my code,

When I use print() function to print list(r)

print(list(r))

my result is an empty list.

But When I write the code:

rList= list(r)

and then

print(rList)

my result is right.

here is my code:

def f(x):
    return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
rList= list(r)
print( list(r) )
print( rList)

here is my result:

[]
[1,4,9,16,25,36,49,64,81]

and here is expected result

[1,4,9,16,25,36,49,64,81]
[1,4,9,16,25,36,49,64,81]
noobshane
  • 43
  • 5

1 Answers1

1

When you cast r (map object) to list it means that you run f function all over your list, and it will be finished. you can not use the result of map twice. like itertools.groupby.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59