Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading