954,557 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

creating lists in a for-loop

Hi

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)):
    popsizelocus_j=[]


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

Elise

echellwig
Newbie Poster
21 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

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

jcao219
Posting Pro in Training
417 posts since Dec 2009
Reputation Points: 28
Solved Threads: 97
 

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

echellwig
Newbie Poster
21 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 
# this works, but see below
# allTheLists = []
# for j in range(int(L)):
#   allTheLists[j] = []
# more pythonic:
allTheLists = [[] for x in range(int(L))]
#...

allTheLists[j].append(jListItem)
printAllTheLiats[listIndex][itemIndex]
# etc
griswolf
Veteran Poster
1,165 posts since Apr 2010
Reputation Points: 344
Solved Threads: 256
 
mainlist = []

for i in range(10):
    a = 'name_'
    b = str(i)
    c = a+b
    c = [i]
    mainlist.append((a+b)+'_st00f')
    
print(mainlist)


That?

Mensa180
Light Poster
31 posts since Oct 2009
Reputation Points: 13
Solved Threads: 7
 

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
L='10'
allthelists = [[] for x in range(int(L))]
#...
j=5
newitem=['abc']
allthelists[j]=newitem ## wrong, or more dangerous
##allthelists[j]=newitem[:] ## right, or safer, copy by [:], newitem does not change

moreitem='def'

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.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: