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)=[]
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)=[]
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)}
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
.
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.
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