0

I am trying to define a series of variables in a quick way. eg:

variable_names=[a,b,c,d,e,f,g]

Python won't allow me to do that unless I define each element first. Is there a quick way to define all of them with none value so that I can assign values to those elements later? Because I want to use a for loop to assign values to elements in variable_names.

Moreover, it there a way I can create variables names according to a specific string?

For example: temp='01'

I want to have variable_names changes to [a01,b01,c01,d01,e01,f01,g01], the elements are all variables that can be assigned values not strings.

I will be really appreciated if anyone can help.

1 Answer 1

1

It sounds like you may be better off with using a dictionary. A dictionary would allow you to define values on the fly and easily loop over the keys/values later as needed.

If that works for you, you can use defaultdict to create a dictionary with values defaulting to None:

from collections import defaultdict # all keys will default to myvalues = defaultdict(lambda: None) # you can check that values are None assert myvalues['newkey'] == None 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the help. But I do not quite understand. I try to set up like: from collections import defaultdict variables=defaultdict(lambda: None) assert variables['newkey'] == None but newkey is not a variable that I can assign value
Yes, it's a dictionary to which you can assign values to specific keys. It's a change in the way you're proposing to handle data. Ask yourself do you really need to have variables? Are dictionary key/value pairs enough?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.