Let's say I have a function f() that takes a list and returns a mutation of that list. If I want to apply that function to five member variables in my class instance (i), I can do this:
for x in [i.a, i.b, i.c, i.d, i.e]:
x[:] = f(x)
1) Is there a more elegant way? I don't want f() to modify the passed list.
2) If my variables hold a simple integer (which won't work with the slice notation), is there also a way? (f() would also take & return an integer in this case)
Another solution, though it's probably not elegant:
for x in ['a', 'b', 'c', 'd', 'e']:
setattr(i, x, f(getattr(i, x)))
Python doesn't have pass by reference. The best you can do is write a function which constructs a new list and assign the result of the function to the original list. Example:
def double_list(x):
return [item * 2 for item in x]
nums = [1, 2, 3, 4]
nums = double_list(nums) # now [2, 4, 6, 8]
Or better yet:
nums = map(lambda x: x * 2, nums)
Super simple example, but you get the idea. If you want to change a list from a function you'll have to return the altered list and assign that to the original.
You might be able to hack up a solution, but it's best just to do it the normal way.
It occurs to me that I don't actually know what you're trying to do, specifically. Perhaps if you were to clarify your specific task we could come up with a solution that Python will permit?
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