1

I have a function(x). I have also several dctionaries items that will go as function() argument x. I need to write a dynamic name for x using for loop. In PHP used to be simple, but here I cannot find a simple way. I see posts about creating new dictionaries etc. very complicated. Am I missing something? I thought Python was extra simplistic.

EDIT:

I need this in a dynamic way where a number is replaced with i:

for i in range(1, 100):
    function(x1)

I cannot write function(x1), function(x2), function(x3) 99 times. How to incorporate i in a simple way without creating dictionaries or lists etc.

Maybe it is not possible the way I want, because x1, x2, x3, ... x99 are dictionaries and also object and cannot generate their names in a simple way taking x and adding i at the end to make it x1, can I?

EDIT ends.

I need to add i at the end or a dictionary name:

for i in range(1, 100):
    z = 'n'+str(i) # or something like this
    function(m.''.i) # this is only an attempt, which is incorrect.
cabavyras
  • 59
  • 7
  • 2
    Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – wjandrea May 10 '20 at 22:50
  • 2
    This sounds like an [x/y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Please show what you’re actually trying to accomplish. Right now it looks like you are just passing strings to an undefined function. – Mark May 10 '20 at 22:51
  • 2
    "How to incorporate i in a simple way without creating dictionaries or lists etc." Adding each of your objects to a list as you create it and then iterating over that list when you need to access them would be substantially simpler than what you're trying to do. On top of this, what you're looking to do is fragile, as it makes assumptions about the number of variables (your loop length needs to match the number of variables, whereas iterating over a list of the variables will always catch them all). If you definitely wanted this you could use `eval('x'+str(i))`, but I advise against it. – Oliver.R May 10 '20 at 23:28
  • Is this an issue of creating the variables or referencing them? – Daniel Walker May 11 '20 at 01:15

1 Answers1

0

As others have pointed out in comments, this is probably an indication that you need to refactor the rest of your code so that the data is passed as a list rather than 99 individual variables.

If you do need to access all the values like this, and they're fields on an object, you can use the getattr() function:

for i in range(1, 100):
    z = 'n'+str(i)
    function(getattr(m, z))

However, if at all possible, do modify the rest of the code so that the data is in a list or similar.

Jiří Baum
  • 6,697
  • 2
  • 17
  • 17