0

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?

Anubhav Dinkar
  • 343
  • 4
  • 16
  • 3
    If you're not able to use a list then it sounds more like a much bigger problem, you should ask about the problem you're trying to solve by doing this – Sayse Jul 15 '19 at 09:29
  • 5
    [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Sayse Jul 15 '19 at 09:30
  • I stated my problem: I just want to optimise that block of code (my code has 15 such variables, all declared the same way; I want to know if instead of 15, I can do it in fewer lines of code). To be clear, I am not running into any issues because of the above declaration. I just want optimisation – Anubhav Dinkar Jul 15 '19 at 09:39
  • You say that you are not satisfied with putting it all in a list, but what about using a dict or a namedtuple instead, as explained [here](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables)? – Georgy Jul 15 '19 at 09:45
  • 1
    @Alex, it is an in-built module, in collections. so, by saying defaultdict(list), I declare a dictionary where the values are lists – Anubhav Dinkar Jul 15 '19 at 09:51

3 Answers3

2

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.

Alireza HI
  • 1,873
  • 1
  • 12
  • 20
1

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!

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
1

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), ...
Alex
  • 5,759
  • 1
  • 32
  • 47