In python create a list with a variable in the name
41,007
Solution 1
why wouldn't you do a dictionary of lists?
y = {}
for a in range (0,16777216):
y[a] = []
also for brevity: https://stackoverflow.com/a/1747827/884453
y = {a : [] for a in range(0,16777216)}
Solution 2
Not sure if this is quite what you want but couldn't you emulate the same behavior by simply creating a list of lists? So your_list[0]
would correspond to y0
.
Solution 3
The answer is: don't. Instead create a list so that you access the variables with y[0]
, y[1]
, etc. See the accepted answer here for info.
Solution 4
Maybe you should check out defaultdict
form collection import defaultdict
# This will lazily create lists on demand
y = defaultdict(list)
Also if you want a constraint on the key override the default __getitem__
function like the following...
def __getitem__(self, item):
if isintance(item, int) and 0 < item < 16777216:
return defaultdict.__getitem__(self, item)
else:
raise KeyError
Author by
Admin
Updated on July 30, 2022Comments
-
Admin almost 2 years
I'm trying to generate a series of (empty) lists using a for loop in python, and I want the name of the list to include a variable. e.g. y0, y1, y2 etc. Ideally looking something like this:
for a in range (0,16777216): global y(a)=[]
-
kojiro over 11 yearsExcept all the keys are integers, so perhaps a list of lists or sparse array?
-
Francis Yaconiello over 11 yearsi typo'd that a, it wasn't supposed to be a string. fixed.
-
Burhan Khalid over 11 yearsYou should mark this question as a duplicate to the one you linked.
-
Francis Yaconiello over 11 yearsadded dict comprehension