Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_item(self, item):         self.attached.append(item) 

If I use this:

D = Dummy() items = [1, 2, 3, 4] for item in items:     D.attach_item(item) 

I indeed get D.attached = [1, 2, 3, 4]. But if I map the function attach_item to the items, D.attached remains empty.

map(D.attach_item, items) 

What is it doing?

like image 304
Mathieu Avatar asked Aug 03 '18 10:08

Mathieu


People also ask

What is the difference between map and forEach?

Differences between forEach() and map() methods: The forEach() method does not create a new array based on the given array. The map() method creates an entirely new array. The forEach() method returns “undefined“. The map() method returns the newly created array according to the provided callback function.

Which is faster for loop or map?

map() takes about 2,000ms, whereas a for loop takes about 250ms.

Is map function faster than for loop Javascript?

Array.map vs for vs for..of map((x) => x. a + x. b); Loops are also much faster here.

Can you describe the main difference between a .forEach loop and a map ()?

The main difference between map and forEach is that the map method returns a new array by applying the callback function on each element of an array, while the forEach method doesn't return anything. You can use the forEach method to mutate the source array, but this isn't really the way it's meant to be used.


2 Answers

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.

like image 67
Farbod Shahinfar Avatar answered Sep 27 '22 22:09

Farbod Shahinfar


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.

like image 28
Lev Zakharov Avatar answered Sep 27 '22 22:09

Lev Zakharov