0

Hello I am currently doing a project were I need up to 30.000 variables, which will be created dynamically. My problem however is accessing said variables dynamically , storing them in an array and accessing them like this works but I'd like to access them by name only. My code looks like:

NG=10
for i in range(1, NG+1 ):
    globals()[f"u_{i}"] = i
    print(u_{i})

Declaring variables like this works and they can be accessed by typing u_1, but the above print statement breaks the code. Is there an option to access a variable similar to this in python?

2
  • Dynamically creating variable name can be done using globals() which is error prone. Use dictionary for sanity of your code Commented Nov 9, 2021 at 14:39
  • For your example change the print statement to print(f'u_{i}') Commented Nov 9, 2021 at 14:41

2 Answers 2

2

You can access it the same way you set it:

globals()[f"u_{i}"]

Except I highly recommend you NOT to use global variables. You can use a dictionary; eg.

data = {}

data["some_key"] = 123
print(data["some_key"])

This will work the same way as does with global variables, except not having the pain of global variables.

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

Comments

0

Using a Dictionary would be the best option if you ask me. Just to give an example of a dummy assignment:

import random
a={} # the dictionary
random.seed(5)
for i in range(30000):
  a['u'+str(i+1)]=random.random() # Or whatever value you want to put in the variable  
print(a['u1']) # First variable and so on...
print(a['u2'])

2 Comments

ok that might be more sensible, but how do I access those dynamically, like print(a[ 'ui' ])?
Yes. You can either access them (if you just want to view) by print. If you want to use the variable somewhere, just reference as a['u1'] (or whatever term you need).

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.