Let's say I have a bunch of instances of the following class:
class Test:
def __init__(self):
self.x = 1
tests = [Test() for _ in range(10)]
Now, let's say I want to update x
for each of the instances to range(10)
. What's a good, pythonic way to do that?
The most straightforward would be something like:
for t, val in zip(tests,range(10)):
t.x = val
Is it possible to do it in a list comprehension?
[z[0].x = z[1] for z in zip(tests, range(10))]
gives an error. I guess you could add a setter method in the function and call that?
class Test:
def __init__(self):
self.x = 1
def setter(self, val):
self.x = val
tests = [Test() for _ in range(10)]
[z[0].setter(z[1]) for z in zip(tests, range(10)]
The for loop starts to look better and better. Is that the way to go?