0

It's probably a dumb Python question, anyway: let's say I have a function that takes an object as parameter and returns a new one, letting the input object untouched. I want to apply such function to multiple objects, x1, ..., xn, and I want the output to be named the same as the input, ie x1,...xn.

Basically, it would be x1=f(x1),...,xn=f(xn). But I don't want to repeat n times the calls to f. Is there a Pythonic way to do it?

Edit: I would like to know if a pack-apply-unpack pattern exists, such as x1,...,xn = something_that_applies_f(x1,...,xn)

Clej
  • 416
  • 3
  • 13
  • 1
    It sounds like your data should probably be stored in a list (or possibly a dictionary) instead of lots of individual variables. Then you could use a for loop or list comprehension. – CrazyChucky Feb 08 '23 at 23:33
  • Well, I have three variables actually. The issue is, performing a list comprehension does not solve my naming problem. My list name would not change, but I wish I could distinguish my variables in the naming itself. Maybe I should use a dictionary though. Is there not a pack-apply-unpack pattern in Python? – Clej Feb 08 '23 at 23:43
  • 2
    If you're going to insist on having separate variables for each object, then writing multiple calls to the function is the only way to do this. Far better to have all the objects in a list (or tuple, or other container), so that you can loop over them: `x = [f(item) for item in x]` would do the entire job here. – jasonharper Feb 08 '23 at 23:43
  • 1
    Related: [How do I create variable variables?](/q/1373164/4518341) From the top answer: *"For cases where you're thinking of doing something like `var1, var2, ...`, a list may be more appropriate"* (paraphrased). And [this answer](/a/38972761/4518341) has more explanation. – wjandrea Feb 08 '23 at 23:57

0 Answers0