0

Is their anything wrong I have done or I did call it in a wrong way?

In:

map(lambda x: x * 3, [1, 2, 3])

Out:

<map object at 0x000001D06DF202E8>
Primusa
  • 13,136
  • 3
  • 33
  • 53
  • 1
    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) – pault Apr 19 '18 at 01:55
  • Which version of python? And what do you want to happen? In python 2, `map` returns as list. In python 3 its an iterator that only emits results as you iterate it. – tdelaney Apr 19 '18 at 02:21
  • There is nothing really wrong with defining it before you use it, but it can only be consumed once. That might be exactly what you want, but usually a map is used as part of an iteration in a for or list comprehension. – tdelaney Apr 19 '18 at 02:26

1 Answers1

2

In python3 map is a generator, so it returns a generator object instead of a list. You can easily convert it into a list though:

list(map(lambda x: x * 3, [1, 2, 3]))

However as Julien said list comprehension is preferable if you are just trying to make a list:

[x*3 for x in [1,2,3]]

The main use of map is its lazy evaluation. This means that the entire set of results isn't all loaded into memory at once.

For instance:

a = map(str, range(100000))
for i in a:
    ...

In this situation a map would be preferable because you are not loading 100,000 strings into memory like a list comp would do.

Primusa
  • 13,136
  • 3
  • 33
  • 53
  • 1
    if you are after a list in the end, list comprehension is better as (arguably) clearer and more concise: `[x*3 for x in [1,2,3]]` – Julien Apr 19 '18 at 01:24
  • Listifying a map object will create entire list in memory. Think of the case where your list cannot fit in memory and this the case where map comes handy. You can iterate one element at a time without running out of memory. – Sohaib Farooqi Apr 19 '18 at 01:30
  • I think he is after a list so that's why i added `list()`. I'll specify its use as a memory saving generator though. – Primusa Apr 19 '18 at 01:30
  • Even in the `a = map(str, range(100000))` case, `a = (str(i) for i in range(1000000))` would be preferred. – tdelaney Apr 19 '18 at 02:19
  • so you are telling me that with list comps and generator expressions map is pretty much useless – Primusa Apr 19 '18 at 02:21
  • @Primusa - Yes. Guido was never really happy with filter, map and reduce as they all are done natively in the language. – tdelaney Apr 19 '18 at 02:25