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?

5
  • 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 Commented Jul 15, 2019 at 9:29
  • 5
    What is the XY problem? Commented Jul 15, 2019 at 9: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 Commented Jul 15, 2019 at 9: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? Commented Jul 15, 2019 at 9: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 Commented Jul 15, 2019 at 9:51

3 Answers 3

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.

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

Comments

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!

Comments

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), ...

Comments

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.