0

I have defined a factorial function which looks as below:

def fact(n):
    return 1 if n < 2 else n * fact(n-1)

Now, I am running map function as below:

results = map(fact, range(1,5))
for x in results:
    print(x)

Output:
    1
    2
    6
    24

I am completely understanding the above output. However, if I run the same for loop again I am getting a blank output which I am not able to understand.

for x in results:
    print(x)

Output:
meallhour
  • 13,921
  • 21
  • 60
  • 117

2 Answers2

1

That's because in python3 map function returns a iterator. When you traverse generator it becomes exhausted and empty, so trying to traverse it again is like traverse empty list.

print(results) # <map object at 0x10a392310>

if you want to traverse it more than once, you can convert it to list

results = list(map(fact, range(1,5)))
kosciej16
  • 6,294
  • 1
  • 18
  • 29
1

results is a map object, which is a generator. Elements are generated as you iterate through the map, and it doesn't reset when you start a new iteration.

If you want it to behave like a list, you could explicitly convert the map to a list like this:

results = list(map(fact, range(1,5)))

or just use a list comprehension instead of map:

results = [fact(n) for n in range(1, 5)]
Samwise
  • 68,105
  • 3
  • 30
  • 44