I’ve been playing around with the map function in Python and I was looking for some help in understanding the following behaviour:
foo="12345"
print map(int,foo)
gives you [1, 2, 3, 4, 5]. Obviously int(foo) spits out 12345. So what exactly is happening? Since strings are iterable by character, would the above two lines be synonymous with
print [int(x) for x in foo]
I know they will output the same result but is there anything different going on behind the scenes? Is one more efficient or better than another? Is one more “pythonic”?
Thanks a lot!
map()may be somewhat faster than using list comprehension in some cases and in some cases map is slower than list comprehensions.when using a built-in function:
with
lambda,map()becomes slow:But, in python 3x
map()returns a map object, i.e. an iterator