0

Let's say I have multiple lists called level_1, level_2, level_3.. Now I want to loop through all of them, but want to use list 1 on idx 1, list 2 on idx 2, .. My solution would be something like this:

for idx, level in enumerate(??): -- #Don't know what to insert here
    if idx == 1:
        print(level[0])
    elif idx == 2:
        print(level[1])

Is there a way to create the list name you're enumerating through dynamically? Like this:

for idx, level in enumerate(level_+idx):
    print(level[0])
    print(level[1])
Tomblarom
  • 1,429
  • 1
  • 15
  • 38
  • 9
    just put your lists in a list – Hamms Jul 21 '17 at 21:50
  • 1
    There is, but this is actually bad design. The only good way to do it, is either prevent yourself from getting that many lists (put these in a list, dictionary,...) or by constructing a list `enumerate([level_1,level_2,...])`. – Willem Van Onsem Jul 21 '17 at 21:50
  • Don't do that. Put all the lists in another list. Dynamically creating variables is almost always the wrong thing to do. – Carcigenicate Jul 21 '17 at 21:51
  • Don't do this. Just *use another container to hold your lists*. `for idx, level in enumerate((list1,list2,list3,list4)): ...` – juanpa.arrivillaga Jul 21 '17 at 21:51
  • The non-insane way of dealing with situations like this is to use a list of lists, rather than dynamically generating variable names. – jasonharper Jul 21 '17 at 21:51
  • Thank you all. Helped me a lot :) I'm completely new to python and it's not as easy as I thought ^^ – Tomblarom Jul 21 '17 at 22:07

1 Answers1

0

You can create a list which contains all of the lists and loop through it instead of using multiple if/else statements, for example:

big_list = [level_1, level_2, level_3]
for i, lst in enumerate(big_list):
    print lst[i]
Mohd
  • 5,523
  • 7
  • 19
  • 30