why is a map object couldn't be assigned to a variable when it is printed beforehand as a list object

lst=[‘a’,’xyz’, ‘summer’, ‘spring’]

def it(x):
    return str(x).upper()

map_iterator=map(lambda x: x.upper(), lst)
print(map_iterator)
print(type(map_iterator))
#print(list(map_iterator))
x=list(map_iterator)


for i in x:
    print(i, end=' ')

print('')
print('****************************************')
#lst2=['asd','x', 'sum', 'ring']
map_iter2=map(it,lst)
print(map_iter2)
print(type(map_iter2))
print(list(map_iter2))
y=list(map_iter2)

for i in y:
    print(i, end=' ')

output:
<map object at 0x7ffff7578150>
<class 'map'>
A XYZ SUMMER SPRING 
****************************************
<map object at 0x7ffff7578f10>
<class 'map'>
['A', 'XYZ', 'SUMMER', 'SPRING']

Executed in: 0.025 sec(s)
Memory: 4220 kilobyte(s)

When i print the map object converting to a list, assignment to a variable and iterating over it is returning an empty list. why is that?

>Solution :

map returns an iterator, as you have seen. once an iterator is consumed, it cannot be "re-consumed" or "rewound"
here:

print(list(map_iter2))  # it is consumed!
y=list(map_iter2)  # it's already empty

if you need to, you can uses itertools.tee as described here

Leave a Reply