6

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
  • 291
  • 1
  • 3
  • 14

6 Answers6

7

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
  • 328,213
  • 58
  • 503
  • 561
vitiral
  • 8,446
  • 8
  • 29
  • 43
2

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!

1

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.

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,967
  • 4
  • 24
  • 34
0

You can try this

k =[]
num = 5
for i in range (0,num,1):
    k = "var" + str(i)

var2 = [12,7,62]
var5 = [2,3,6]
print(var2)
print(var5)
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 04 '23 at 12:39
-2

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")