2

Say I have a list my_list = ['a','b','c'] and I have a set of values my_values = [1,2,3]

Is there a way to iterate through my list and set the values of my_list equal to my_values

for i in range(len(my_list)):

    ## an operation that instantiates my_list[i] as the variable a = my_values[i]

...
>>> print a
1

I just want to do this without copying the text of file that holds the program to a new file, inserting the new lines as strings where they need to go in the program. I'd like to skip the create, rename, destroy, file operations if possible, as I'm dealing with pretty large sets of stuff.

2
  • don't do this. you will regret it. use a dict. Commented Jun 28, 2014 at 1:54
  • Thanks for the warning @Eevee. I know, it seems super foolish, but it's not for a professional project, and will be very safely sand-boxed. Commented Jun 28, 2014 at 9:58

1 Answer 1

2

This is probably hackery that you shouldn't do, but since the globals() dict has all the global variables in it, you can add them to the global dict for the module:

>>> my_list = ['a','b','c']
>>> my_values = [1,2,3]
>>> for k, v in zip(my_list, my_values):
...     globals()[k] = v
... 
>>> a
1
>>> b
2
>>> c
3

But caveat emptor, best not to mix your namespace with your variable values. I don't see anything good coming of it.

I recommend using a normal dict instead to store your values instead of loading them into the global or local namespace.

Sign up to request clarification or add additional context in comments.

2 Comments

That's awesome! Totally works. That saved me so much headache work. Also didn't know the globals were stored like that either. This is cool, I can even just "del globals[key]" when I'm done with my variable. I will definitely come back and vote you up when I get over 15 reputation.
Told you I'd be back!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.