Is that possible, in Python, to update a list of objects in list comprehension or some similar way? For example, I\'d like to set property of all objects in the list:
Ultimately, assignment is a "Statement", not an "Expression", so it can't be used in a lambda expression or list comprehension. You need a regular function to accomplish what you're trying.
There is a builtin which will do it (returning a list of None
):
[setattr(obj,'name','blah') for obj in objects]
But please don't use it. Just use a loop. I doubt that you'll notice any difference in efficiency and a loop is so much more clear.
If you really need a 1-liner (although I don't see why):
for obj in objects: obj.name = "blah"
I find that most people want to use list-comprehensions because someone told them that they are "fast". That's correct, but only for creating a new list. Using a list comprehension for side-effects is unlikely to lead to any performance benefit and your code will suffer in terms of readability. Really, the most important reason to use a list comprehension instead of the equivalent loop with .append
is because it is easier to read.