Python : Using the map function

The problem is that a list is not created. map returns a specific type of generator in Python 3 that is not a list (but rather a 'map object', as you can see). You can try

print(list(squares))

Or just use a list comprehension to obtain a list in the first place (which seems to work better here anyway):

squares = [x**2 for x in range(10)]

map used to return a list in Python 2.x, and the change that was made in Python 3 is described in this section of the documentation:

  • map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

mapreturns a generator, i.e. this is something that can be used to loop over once it's required. To get the actual list, do print(list(squares)). Or

for a in squares:    
    print a

Update: This looks strange at first but imagine you have 1mio numbers. If it would create a list right away, you'd need to allocate memory for 1mio elements, even though you may ever only want to look at one at a time. With a generator, a full list of elements will only be held in memory if necessary.

Tags:

Python

Map