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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With