4

What I would like to do is find a more concise way of creating variables of empty lists that will be similar to each other, with the exception of different numbers at the end.

#For example:
var1 = []
var2 = []
var3 = []
var4 = []
#...
varN = []

#with the end goal of:
var_list = [var1,var2,var3,var4, ... varN]
SchoonSauce
  • 261
  • 1
  • 3
  • 14

5 Answers5

6

Use a list comprehension:

[[] for n in range(N)]

or a simple for loop

empt_lists = []
for n in range(N):
    empt_lists.append([])

Note that [[]]*N does NOT work, it will use the same pointer for all the items!!!

Tim Pietzcker
  • 313,408
  • 56
  • 485
  • 544
vitiral
  • 7,266
  • 5
  • 24
  • 40
1

Ok...possible solution is to generate class attributes, which you can use after:

class MyClass:
    pass
myinstance = MyClass()  # if you want instance for example
setattr(myinstance, "randomname", "desiredvalue")
print myinstance.randomname  # wonderfull!

put it in the list if possible in your case!

0

you can concatenate the variable assignments, if that's what you mean, you can set them all to [] var1, var2, var3 = [] did you want all the variables to be set to an empty array or to actual numbers

nbpeth
  • 2,767
  • 4
  • 21
  • 31
0

Dynamic variables are considered a really bad practice. Hence, I won't be giving a solution that uses them. :)

As @GarrettLinux pointed out, you can easily make a list comprehension that will create a list of lists. You can then access those lists through indexing (i.e. lst[0], lst[1], etc.)

However, if you want those lists to be named (i.e. var1, var2, etc.), which is what I think you were going for, then you can use a defaultdict from collections.defaultdict:

from collections import defaultdict
dct = defaultdict(list)
for i in xrange(5):
    dct["var{}".format(i+1)]

Demo:

>>> dct
defaultdict(<type 'list'>, {'var5': [], 'var4': [], 'var1': [], 'var3': [], 'var2': []})
>>> dct["var1"]
[]
>>> dct["var1"].append('value')
>>> dct["var1"]
['value']
>>> dct
defaultdict(<type 'list'>, {'var5': [], 'var4': [], 'var1': ['value'], 'var3': [], 'var2': []})
>>>

As you can see, this solution closely mimics the effect of dynamic variables.

-1

I also had this question. I ended up making a all of my variables and the making a list with the variable names

var1 = 123456 
var2 = 123457 
list1 = [var1, var2] 
raninput = input("Words") 
if raninput not in list1: 
  print("Hi")