-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

3
  • Generally a bad idea to dynamically create variables. Commented Apr 30, 2021 at 1:24
  • 4
    Does this answer your question? Dynamically Create Variables in For Loop, Python Commented Apr 30, 2021 at 1: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. Commented Apr 30, 2021 at 1:25

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.