Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to modify a list of variables by reference in Python?

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)

like image 389
David P Simons Avatar asked Feb 26 '23 07:02

David P Simons


2 Answers

Another solution, though it's probably not elegant:

for x in ['a', 'b', 'c', 'd', 'e']:
    setattr(i, x, f(getattr(i, x)))
like image 80
Antoine Pelisse Avatar answered Feb 27 '23 20:02

Antoine Pelisse


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.

EDIT

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?

like image 32
Rafe Kettler Avatar answered Feb 27 '23 19:02

Rafe Kettler