1

I have 5 empty lists list1=[], list2=[], list3=[], list4=[], list5=[] and list with 5 variable var_list=[v1, v2, v3, v4, v5]. I want to append each variable inside var_list inside a corresponding empty list. I do that work manually:

list1.append(var_list[0])
list2.append(var_list[1])
list3.append(var_list[2])
list4.append(var_list[3])
list5.append(var_list[4])

I want to do that in for loop, I known the elements of var_list can be called inside loop as var_list[i], but how can I call list in such way, where all variables list with same name and different in numbers. 'list'+str(i) cannot work. Can anyone please help me to do this work in one line inside loop.

hh tt
  • 395
  • 5
  • 22

1 Answers1

1

I suggest you use a dict to hold all the lists. Maybe something like this:

my_lists = {
    'list_{}'.format(i+1): []
    for i in range(5)}

var_list = [1, 2, 3, 4, 5]

for i, elem in enumerate(var_list):
    my_lists['list_{}'.format(i+1)].append(elem)

After running this, my_lists will hold:

{'list_1': [1], 'list_2': [2], 'list_3': [3], 'list_4': [4], 'list_5': [5]}

Note: in this case it is asumend that the order of elements in var_list corresponds to the names of the lists (elem at position i in var_list will go to the list with i in its name).

Ralf
  • 16,086
  • 4
  • 44
  • 68
  • Thank you very much. It is work, but is it the only way? I have huge data. – hh tt Mar 09 '19 at 16:58
  • @hhtt If you want more specific help we need more specific information of what exactly you need. You could ask a new question with more specific information. – Ralf Mar 09 '19 at 18:05