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:
result = [ object.name = "blah" for object in objects]
or with map
function
result = map(object.name = "blah", objects)
Could it be achieved without for-looping with property setting?
(Note: all above examples are intentionally wrong and provided only to express the idea)
You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method.
List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
List comprehension is a complete substitute to for loops, lambda function as well as the functions map() , filter() and reduce() .
Map function is faster than list comprehension when the formula is already defined as a function earlier. So, that map function is used without lambda expression.
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.
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