1

I've been restructuring a project of mine to be more elegant and legible. I've gotten to a point where I want to apply a function to several variables, thus transforming the value of the variable. To my dismay, I've realized that the for loop I was using did not change the value of the variables.

E.g:

    def change_value(x):
        x = x * 2
        return x
    a = 5
    b = 10
    c = 15

    for x in (a,b,c):
        x = change_value(x)

    print(a) #a doesn't actually change.

The reason I want to do this is because I have created several data sets and a method which reshapes them. Rather than explicitly pass each variable through the function on its own line, I would like to find a way to iterate.

Alex Manuele
  • 211
  • 2
  • 4

2 Answers2

1

That doesn't work because x = change_value(x) is just reassigning the local x variable. Reassigning a local like that does not effect the collection being iterated over.

If you have a group of variables that are all of a similar purpose, it may be appropriate to have them in a structure together. The instant benefit is you're able to iterate over the collection and transform the values easily.

If the values don't actually need to be named, you can stick them in a list and map the list:

xs = [1, 2, 3]

changed_xs_comp = [change_value(x) for x in xs]
changed_xs_map = list( map(change_value, xs) )

print(changed_xs_comp, changed_xs_map)) # Prints [2, 4, 6] [2, 4, 6]

Or, if you want names, use a dictionary:

d = {"a":1, "b":2, "c":3}

changed_d = {k:change_value(d[k]) for k in d}

print(changed_d) # Prints {'a': 2, 'b': 4, 'c': 6}

Whether or not grouping them is appropriate requires more context to say, but if they're all needing to be mapped by the same function, that's a strong indicator for me that they likely should be grouped.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • Thanks for your answer. Essentially, the short answer to my question (in my particular code, anyway) is "No, not without grouping your objects into a data structure first". That said, map() became tremendously useful for a later task. I unfortunately am too much a noob to know how to 'accept' your answer, I'm not seeing any means to do so. Perhaps this is because my question has been flagged as duplicate. I'll keep looking. – Alex Manuele Dec 05 '18 at 17:04
  • @AlexManuele Note that list comprehensions are faster and more Pythonic than `map`. I just mentioned both to cover all the bases. – Carcigenicate Dec 05 '18 at 19:05
0

Perhaps you could use the map function:

a, b, c = map(change_value, [a, b, c])
ttamiya
  • 101
  • 4