0

I am using Python 3.5 and I want to assign values to new objects in a loop:

for i in range(10):
    vector_N{}.format(i) = np.random.randint(10,20,10)

I am expecting 10 vectors whose names will be vector_N1, vector_N2 and so on assigned the corresponding random values.

I know that I can create empty list as a container and use it to save all this values but I want exactly this names and not to use list indexing.

Is it possible in python?

  • 3
    There is no good reason to use separate variables with specially structured names instead of using a list or data structure. – BrenBarn Dec 16 '16 at 08:36
  • What?? Why would you even want to do that - this creates completely unpredictable and unmaintainable code. Just use lists or dictionaries for this instead of trying to dynamically create variable names – UnholySheep Dec 16 '16 at 08:37
  • Yeah probably a dict will be ideal for your case. Please check this discussion: http://stackoverflow.com/questions/1060090/changing-variable-names-with-python-for-loops. It answers your question. – afxentios Dec 16 '16 at 08:38
  • For example when I have list and index the elements of my list I can not use autocomplete feature and in the other case I can. E.g.: lst[0] +tab doesn't do anything but vector_N1 does. – Nikoloz Mamisashvili Dec 16 '16 at 08:38
  • it's common and better to use a list for storing a number of different objects. – Acepcs Dec 16 '16 at 08:39
  • What autocomplete feature? also it won't work with dynamically generated variable names anyway. If you really want to do this (against all recommendations) you can directly modify the symbol table, e.g.: using [`globals()`](https://docs.python.org/2/library/functions.html#globals). But to reiterate this is **highly dangerous** and **not recommended** – UnholySheep Dec 16 '16 at 08:46
  • @NikolozMamisashvili There are better ways to have autocomplete-friendly, dinamically created objects. You can ask a new question about that. – Stop harming Monica Dec 16 '16 at 09:53

0 Answers0