I was wondering if there is any way to created a series of lists in a for-loop so that the first list created is named NAME0 or name_0 or indexed in some way. What I have right now is

for j in range(int(L)):

however, this is not working as far as I can tell. Any help would be greatly appreciated!


Recommended Answers

All 5 Replies

I'm not understanding the question at all.
Do you want to create a list of lists?

Yes! That is what I mean. How to create a list of lists.

# this works, but see below
# allTheLists = []
# for j in range(int(L)):
#   allTheLists[j] = []
# more pythonic:
allTheLists = [[] for x in range(int(L))]

# etc
mainlist = []

for i in range(10):
    a = 'name_'
    b = str(i)
    c = a+b
    c = [i]


It is very difficult or error prone to do assignment to list elements so often I prefer to use dicts.

# elements of list are mutable and can be variable reference, not values
allthelists = [[] for x in range(int(L))]
allthelists[j]=newitem ## wrong, or more dangerous
##allthelists[j]=newitem[:] ## right, or safer, copy by [:], newitem does not change


allthelists[j].append(moreitem) ## changes newitem if not copy

print 'New item',newitem

newitem='ghi' ## in this case no problem as newitem overwriten

print "allthelists:"
print allthelists ## element of allthelist did not change

prove to swap commenting in lines 7 and 8.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.