0

What i have understood so far from the map function is that it applies a given function to each item in an iterable and returns the list of the result.

def square(num):
    return num**2

list_num = [1,2,3,4]

considering the above function and the list of numbers as an example.

if we: list(map(square,list_num)) we will get as an output [1,4,9,16].

now comes the part that i am not able to find a sensible explenation of, if i

print(map(square,list_num)) i will get as an output <map object at 0x038B0290>.

My question is, Why am i getting the memory location and not a list when i use the print() function or when use map(square,list_num).

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Ahmed
  • 119
  • 1
  • 13
  • 1
    Because `map` returns a map object, not a list: "Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted." – L3viathan Jan 03 '19 at 16:04
  • Possible duplicate of [Getting a map() to return a list in Python 3.x](https://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x) – jpp Jan 03 '19 at 16:15
  • i understand how to get a list of results from map and how to use it... i just needed a sensible explanation why it outputted memory location when using map alone or with the print function. But Thanks :). – Ahmed Jan 03 '19 at 16:18

1 Answers1

3

map doesn't return a list. It returns a map object that lazily produces results as needed:

print(type(map(int, [1])))
<class 'map'>

It also doesn't override the stringify method which would produce pretty-printed results. That may be because that would require forcing the entire list to be evaluated, and if that's acceptable in your program, you probably shouldn't be using map in the first place; unless you're debugging, in which case use of list is probably fine unless you're dealing with an infinite list.

If you want a full-element print out, explicitly force it by placing it in a list before printing as you saw, or use a strict list production method like a list comprehension.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117