Reputation:
I have a number of lists called: index_1, index_2, index_3, ...., index_n.
What I want is to concatenate them all in a new list.
My code so far:
index_all=[]
for i in range(1,n+1):
index_all = index_all + globals()["index_"+str(i)]
However, I get an error:
KeyError: index_1
Any ideas as to how to solve this?
Upvotes: 1
Views: 497
Reputation: 1012
use list unpacking
cat_list = []
for i in range(1, n+1):
cat_list = [ *cat_list, *globals()['index_'+str(i)] ]
Upvotes: 0
Reputation: 2154
You could try this out:
list1 = [[1,2,3],[4,5,6],[7,8,9]]
def joinAll(mulist):
index_all=[]
for i in mulist:
for u in i:
index_all.append(u)
return index_all
print joinAll(list1)
Upvotes: 1
Reputation: 1628
you may want to use map and filter , and the globals().items() feature:
concat_list = map ( lambda list_var : list_var[1] , filter ( lambda list_var : list_var[0].startswith("list"), globals().items()))
your concat_list is the list of all items from all lists
Upvotes: 1
Reputation: 86
It seems you may just have a naming error, you try to call "index_" + str(i) but your lists are named "list_" + str(i). The following line should work as long as your lists are named list_1, list_2... list_n with no breaks and your n is correct.
index_all = [globals()["list_"+str(i)] for i in range(1, n+1)]
If you want the lists to be flat you can
[item for sublist in index_all for item in sublist]
It might be easier if you can avoid using globals() as it will probably be fragile!
Upvotes: 1