Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Map() problem
#1
list1 = [1,2,3,4,5,6,7,8,9,10]
squared = map(lambda x:x**2, filter(lambda x:x%2==0, list1))
print(squared)
The output i expect is
Output:
4
However, it comes as
Output:
<map object at 0x1076aa150>
Why does this happen? I went through several sites, I tried running code. According to this site, the code is
# Python program to demonstrate working 
# of map. 
  
# Return double of n 
def addition(n): 
    return n + n 
  
# We double all numbers using map() 
numbers = (1, 2, 3, 4) 
result = map(addition, numbers) 
print(list(result)) 
And the output indeed is as expected,
Output:
[2, 4, 6, 8]
I'm confused, why am I getting this problem, and what is it's cause? Any help would be appreciated
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#2
map() returns map object. The other snippet converts the map object to list on line 11. You don't do that.

print(squared)
vs

print(list(result))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
The idea here is that of a lazy sequence - evaluation of the items doesn't happen until you ask for it. One of the things this allows you to do is have potentially infinite sequences. There's a bit of a comparison between Python and Clojure here and it includes references to more pages about laziness.
Reply
#4
A lot more stuff got lazy Sleepy in python 3.
@ndc85430 explain why is it so.

If i run code in Python 2.7 this happens.
>>> list1 = [1,2,3,4,5,6,7,8,9,10]
>>> squared = map(lambda x:x**2, filter(lambda x:x%2==0, list1))
>>> print(squared)
[4, 16, 36, 64, 100]
Reply
#5
Thanks a lot! However, I never knew python 3 was this lazy :D
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020