0
def new(a):
    return a*a

x=map(new,[1,2,3,4,5])
print(x)
print(list(x))
print(tuple(x)) 

output is

<map object at 0x03717298>
[1, 4, 9, 16, 25]
()

why we are getting output as empty tuple with list(x)?

def new(a):
    return a*a

x=map(new,[1,2,3,4,5])
print(x)
# print(list(x))
print(tuple(x))    

output is:

<map object at 0x009E71D8>
(1, 4, 9, 16, 25)

the above code gives the tuple as the answer when we are not using list.

  • `map` objects are iterators, when you use `list(x)` on it, it *consumes* the iterator, if you try to iterate over it again, like `tuple(x)` it will be empty. Switch the order and you'll see – juanpa.arrivillaga Jul 03 '20 at 06:59
  • Once you've iterated the `map` object once (`list(x)`), it is exhausted, so when you try to iterate it again (`tuple(x)`) there are no values left. You need to re-create the object to use it again. – Nick Jul 03 '20 at 07:00
  • @juanpa.arrivillaga I was hunting for an appropriate dupe, do you know one? – Nick Jul 03 '20 at 07:00

1 Answers1

0

becuase map is not a list, it is an iterator. An iterator is something you can apply for loop on and get values one by one. So you need to iterate over it to get values from it one-by-one. The list() function does the same for you! You should use:

def new(a):
    return a*a

x = list(map(new,[1,2,3,4,5]))
print(x)

Similar to list(), the tuple() function iterates over it to return a tuple

def new(a):
    return a*a

x = (map(new,[1,2,3,4,5]))
print(tuple(x))
Shivam Jha
  • 3,160
  • 3
  • 22
  • 36