Skip to content Skip to sidebar Skip to footer

Difference Between A 'for' Loop And Map

From the title, yes there is a difference. Now applied to my scenario: let's consider a class Dummy: class Dummy: def __init__(self): self.attached = [] def attach

Solution 1:

A very interesting question which has an interesting answer.

The map function returns a Map object which is iterable. map is performing its calculation lazily so the function wouldn't get called unless you iterate that object.

So if you do:

x = map(D.attach_item, items)
for i in x:
    continue

The expected result will show up.

Solution 2:

map only creates an iterator. You should iterate through it to add items into D.attached. Like this:

D = Dummy()
items = [1, 2, 3, 4]
list(map(D.attach_item, items))

Yep, don't do it in your code:) But the example is just useful for understanding.

Solution 3:

Quoting the documentation

Return an iterator that applies function to every item of iterable, yielding the results.

which means you have to collect the iterator, e.g.

list(map(D.attach_item, items))

> [None, None, None, None]

Hmmm, strange. Why None, None, ...

Yes, you can convert any loop in a map statement, but it's not always useful. Map takes a parameter and does something with it (in most cases) an returns it, without side effects! Here's an example:

defadd(a):
    return a + 3list(map(add, items))

> [4, 5, 6, 7]

The true power comes, when you combine it with other functions like filter

defadd(a):
    return a + 3defodd(a):
    return a % 2 == 1list(map(add, filter(odd, items)))

> [4, 6]

Post a Comment for "Difference Between A 'for' Loop And Map"