An elegant way to change a list of variables by reference in Python?

Say I have a function f () that takes a list and returns a mutation of this list. If I want to apply this function to five member variables in an instance of my class (i), I can do this:

for x in [ia, ib, ic, id, ie]: x[:] = f(x) 

1) Is there a more elegant way? I do not want f () to modify the passed list.

2) If my variables contain a prime integer (which will not work with the slice note), is there also a way? (f () also takes and returns an integer in this case)

+4
source share
3 answers

Another solution, although it is probably not elegant:

 for x in ['a', 'b', 'c', 'd', 'e']: setattr(i, x, f(getattr(i, x))) 
+4
source

Python does not have access to the link. The best you can do is write a function that creates a new list and assigns 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 even better:

 nums = map(lambda x: x * 2, nums) 

A super simple example, but you get this idea. If you want to change the list from a function, you will have to return the changed list and assign it to the original.

You may be able to crack the solution, but it’s best to do it the usual way.

EDIT

It seems to me that I really do not know what you are trying to do, in particular. Perhaps if you clarified your specific task, we could find a solution resolved by Python?

+2
source

Ultimately, what you want to do is incompatible with how Python is structured. You have the most elegant way to do this already if your variables are lists, but this is not possible with numbers.

This is because variables do not exist in Python. Links do. So ix not a list, it is a link to a list. Similarly, if it refers to a number. Therefore, if ix refers to y , then ix = z does not actually change the value of y , it changes the location in memory that ix points to.

In most cases, variables are treated as fields containing a value. The name is on the box. In python, values ​​are fundamental, and "variables" are just tags that hang by a specific value. It is very nice when you get used to it.

In the case of a list, you can use the slice assignment, as you already do. This will allow all links to the list to see the changes, since you yourself change the list object. In the case of a number, there is no way to do this because numbers are immutable objects in Python. It makes sense. Five to five, and little can be done to change it. If you know or can define an attribute name, you can use setattr to change it, but that will not change other links that may already exist.

As Rafe Kettler says, if you can be more specific about what you really want to do, then we can come up with a simple elegant way to do this.

+2
source

Source: https://habr.com/ru/post/1337103/


All Articles