Use of map() in python

Asked

Viewed 114 times

1

Searching on this site https://pythonhelp.wordpress.com/2012/05/13/map-reduce-filter-e-lambda/ vi o uso do map(). But in the terminal the first example is not printing a list.

import math
lista1 = [1,4,9,16]
lista2 = map(math.sqrt,lista1)
print(lista2)

<map object at 0x00C84770> 

But when a list comprehensions is done it works, [math.sqrt(x) for x in lista1], has as output a correct list. What is the difference?

  • map returns an interactor, vc can unpack so, Lista2 = [*map(Math.sqrt,list1)]

1 answer

0


The map() is a function that returns an iterator object. You need to use it a for loop or convert it to another type of sequence as for example list. See how it would look:

import math
lista1 = [1,4,9,16]
lista2 = list(map(math.sqrt,lista1))
print(lista2)

[1.0, 2.0, 3.0, 4.0]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.