-2

When assigning many variables, (or simply instantiating), one could do:

list_0, list_1, list_2 = [], [], []

which will make three variables with empty lists.

Hypothetically, if one were to make 1,000 empty lists:

list_0, ... , list_999 = [], ... , []

which seems quite tedious if one were to use the top approach.

In such a case, and my question, is it okay to use globals(), such as:

for i in range(1000):
    globals()["list_%s" % i] = []

I haven't really seen such method at SO for many times, and started to wonder if it is because of some downsides I'm not aware of.

I've googled with different keywords, and did find some use cases in second answer of this post, and so on, but ended up with no fruitful result.

Any insight would be highly appreciated. Thanks!

Chris
  • 29,127
  • 3
  • 28
  • 51
  • 6
    Yes, this is a bad idea in most cases, just make a list of lists instead. [See this](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables). – Norrius Feb 18 '19 at 09:48
  • 3
    Dynamic variable names are doubly bad. – Dan D. Feb 18 '19 at 09:56

1 Answers1

3

Short answer:

Yes, it is a bad idea.

Long answer:

I agree with @Norrius, actually, all things to assign like that aren't good, here is the list:

  1. exec, Bad

  2. globals, Bad

The discussion about exec and eval:

Why is using 'eval' a bad practice?

Also, as you see, there is a answer using setattr,

And here is @Nadia's comment about eval:

Yes, using eval is a bad practice. Just to name a few reasons:

  1. There is almost always a better way to do it
  2. Very dangerous and insecure
  3. Makes debugging difficult
  4. Slow

But also, see this:

How do I create a variable number of variables?

Saying dictionary is the mostly and generally the best:

>>> d = {'a':[1,2,3]}
>>> d['b']=[4,5,6]
>>> d
{'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114