Anubhav Dinkar
Anubhav Dinkar

Reputation: 413

How can I declare multiple similar variables in Python?

I have several variables, each having a different use, which are declared in the following way:

a= defaultdict(list)
b= defaultdict(list)
c= defaultdict(list)
d= defaultdict(list)
e= defaultdict(list)
f= defaultdict(list)
#and several more such variables

With regard to this question, a list will not reduce the effort, as I need to use all these variables in different tasks (If I create a list, I will again have to declare each one of these variables by list indices, which is a similar effort)

Is there a way I can reduce the number of lines in declaring all these variables?

Upvotes: 0

Views: 115

Answers (3)

Alex
Alex

Reputation: 6047

The shortest is probably:

a,b,c,d,e,f = [defaultdict(list)]*6

which is a shorthand way of saying:

a,b,c,d,e,f = defaultdict(list), defaultdict(list), defaultdict(list), ...

Upvotes: 1

Alireza HI
Alireza HI

Reputation: 1933

You can assign each with this format:

a,b,c,d,e,f = [defaultdict(list) for i in range(6)]

In this way you are creating a list of defaultdict(list) which will assign each of them to a variable. So each variable will be initiated to defaultdict(list) independent to the other variables.

6 would be number of your variables.

Upvotes: 2

Alexandre B.
Alexandre B.

Reputation: 5500

Not sure to understand the problem... but maybe you are looking to eval. You can declare dynamically variable from string.

An example:

for i in range(50):
    exec('my_var_%s = {"a":%s}'% (i,i))

print(my_var_1)
# {'a': 1}

I also advice you to have a look at this discussion. (even if it's for eval function).

Hope that helps!

Upvotes: 1

Related Questions