-2

Is there a way to iteratively rename objects in python? I'm trying to code something along the lines of:

for i in range(5000):
phat_i = i/5000
print(i/5000)

It doesn't seem like this will work because even if this created a new objected named "phat_i," it seems like it would just redefine that object for each "i." Instead, I want to create new objects "phat_1," "phat_2," etc. for each "i."

I've already looked at this question but the only answer to it seems to have not answered my question. Maya Python: Renaming object with for loops

Aaron
  • 181
  • 5
  • Generally a bad idea to dynamically create variables. – ddejohn Apr 30 '21 at 01:24
  • 4
    Does this answer your question? [Dynamically Create Variables in For Loop, Python](https://stackoverflow.com/questions/19191730/dynamically-create-variables-in-for-loop-python) – ddejohn Apr 30 '21 at 01:25
  • There are dozens of posts like this ^^^ and most of them usually say the same thing: *don't create variables dynamically*. There are zero good reasons to do so, and there are likely a few dozen ways to achieve what you need with something safer. – ddejohn Apr 30 '21 at 01:25

1 Answers1

2

eval() and exec() could be used but they're bad practices since they can be exploited.

Instead, I suggest using dictionaries.

phat_ = {}
for i in range(5000):
    phat_[i] = i/5000
12944qwerty
  • 2,001
  • 1
  • 10
  • 30