0

might be a dumb question but why when I try to use map() function on an already existing list:

nums = [1,2,3,4,5]
result = map(lambda num: num+num , nums)
print(result)

it returns me: <map object at 0x7f41cef17130> , instead of my result;

on the contrary when I do this:

nums = 1,2,3,4,5
result = list(map(lambda num: num+num , nums))
print(result)

it does print me my desired result: [2, 4, 6, 8, 10]

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 2
    And your question is...? That's just how map works in python3. – Sören Nov 24 '22 at 21:05
  • 2
    `map` returns a `map` object *always*. `map` objects are iterators. You need to iterate over the object to get each individual value. One way is to create a `list` out of it, or a `tuple`, or whatever you want. – juanpa.arrivillaga Nov 24 '22 at 21:05
  • 1
    There's no difference whether or not `map()` was called on an "existing list", just if you called `list()` on the result of `map()`. – Edward Peters Nov 24 '22 at 21:06
  • Right, the distinction isn't what map is being used on, in your case, you use map on a list first then on a tuple, but the behavior would be *exactly the same*, the difference is that you *create* a list in the second case, from the iterator. – juanpa.arrivillaga Nov 24 '22 at 21:10
  • I actually think the accepted answer in the linked duplicate is not very helpful. You should read the other answers. – juanpa.arrivillaga Nov 24 '22 at 21:37

1 Answers1

0

Others have already said this. In python you have a few datatypes that don't show the values directly and require another function. This is one of them. Others are a generator:

(x for x in range(5))

<generator object at ....>

And zip:

zip([1,2], [1,2])

<zip at ....>

What that means is basically where in the memory it is saved

In general just know that whenever you see python return something like that, but you wanted a datatype (like a list or a string), that means you still need to do something to it. So:

list(map(...))

list(zip(...))

etc.

Ahek
  • 47
  • 4