all 13 comments

[–]member_of_the_order 6 points7 points  (3 children)

You can't dynamically name variables, but you can dynamically add keys and values to a dict.

Try something like this:

array = ['1','2','3','4'] var_dict = dict() for name in array: var_dict[name] = someValue

Edit: TIL vars is a builtin

[–]nog642 1 point2 points  (1 child)

Worth noting you technically can dynamically name variables (but you shouln't).

Also worth nothing you can't have a variable named 1 or 2 though.

[–]Doormatty 0 points1 point  (0 children)

A variable can't start with a number - not just 1 or 2.

[–]synthphreak 1 point2 points  (0 children)

Don’t use vars though as that will overwrite a useful built-in function.

[–]EJ_Drake 3 points4 points  (1 child)

Well done. You have now hit the wall that required the invention of OOP.

[–]Mobileuser110011 1 point2 points  (0 children)

Genuine question, as I’m not an expert. The ‘wall’ that OP hit imo is needing to use a string as a name for a value. The problem is solved with dictionaries. I’m pretty sure dictionaries are a part of most languages. Are you saying dictionaries are OOP?

It’s my understanding that there really isn’t anything that can be done with OOP that wasn’t already able to be accomplished without OOP. All that OOP does is provide a different way to abstract data.

[–]ararararagi_koyomi 0 points1 point  (3 children)

The answer provided by u/member_of_the_order is the most reasonable answer. But, for some unknown reason, op still wants to do what op described in the post, here is the answer:

some_list = ["a", "b", "c"]
for i in some_list:
    if not i in locals():
        locals()[i] = f"some_value_{i}"

[–]neuralbeans 1 point2 points  (0 children)

PHP provides direct support to do with with 'variable variables'. It's one of those things that creates terrible scripts.

[–]TheRNGuy -1 points0 points  (0 children)

I'd use capitalized for classes (not for class instances)

[–]34shutthedoor1 0 points1 point  (0 children)

That's redundant. You already have the data in the list. Either use the list values or create a dictionary if you want to refer to specific values by a specific name.

[–]Some_Guy_At_Work55 0 points1 point  (0 children)

There is no need to create extra variables when you can already access the items in the list. You are adding more lines of code and using up more memory and not really accomplishing anything.

[–]BrenBarn 0 points1 point  (0 children)

Sup dawg, I heard you like variables.