What is the difference between map objects and generator objects?

Question:

Which of these is best to use in which situations? I’m referring to object made with map(), generator expressions, and generator functions.

Here’s code I used to view these objects.

str_ints = (str(x)for x in range(3))
f = len
map_obj = map(f, str_ints)
gen_obj_from_gen_expression = (f(e) for e in str_ints)

def gen_f():
  for e in str_ints:
    yield f(e)

gen_obj_from_function = gen_f()
for obj in (map_obj, gen_obj_from_gen_expression, gen_obj_from_function):
  print(f'object: {obj}ntype: {type(obj)}n')

output:

object: <map object at 0x7f425c0f3f98>
type: <class 'map'>

object: <generator object <genexpr> at 0x7f425c1573b8>
type: <class 'generator'>

object: <generator object gen_f at 0x7f425c157570>
type: <class 'generator'>
Asked By: David Smolinski

||

Answers:

There is very little difference between these objects. The reason they are different objects comes from the ability of the map function to take multiple iterables.

In that case, it iterates over all of them and on every iteration, invokes the function with elements from every one of them. It stops when the shortest iterable is finished, which is not something a regular generator is capable of doing.

Answered By: Daniel Geffen