Search code examples
pythonloopsvariablessequencevariable-names

Call a sequence of variables with same name inside loop in python


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.


Solution

  • 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).