3

I have a list of objects and I want to change the value of an attribute of all the objects (to the same value-NewValue).

Is map() more efficient than a normal for loop in this situation where the function(lambda) doesn't return any value?

map ( lambda x: x.attribute = NewValue, li)

vs

for i in li:
    i.attribute = NewValue
unholysampler
  • 17,141
  • 7
  • 47
  • 64
Graddy
  • 2,828
  • 5
  • 19
  • 25
  • [This answer](http://stackoverflow.com/questions/1892324/why-program-functionally-in-python/1892614#1892614) is very enlightening. Also, if you want to know whether one approach is more efficient than another, use [timeit](http://docs.python.org/library/timeit.html). – Björn Pollex Jan 30 '12 at 12:09

2 Answers2

5

You cannot assign in a lambda, but lambda is just shorthand for a function so you could:

def set_it(x):
    x.attribute = new_value
map(set_it, li)

compared with the obvious:

for x in li:
    x.attribute = new_value

A general rule of thumb for map vs a for loop (whether a list comprehension or written out in full) is that map may be faster if and only if it doesn't call a function written in Python. So expect that map will be slower in this case. Also the straight for loop doesn't create and then throw away an unwanted intermediate list so expect the map to lose out even more than usual.

Duncan
  • 92,073
  • 11
  • 122
  • 156
  • thanks..the second part of the answer is what I was looking for though my example in the question was very bad :D – Graddy Jan 30 '12 at 12:19
0

Your approach won't work. It is not possible to assign a value in a lambda construct.

glglgl
  • 89,107
  • 13
  • 149
  • 217