0

I am working on a program that store information in different lists using globals. The numer of lists changes everytime the program runs. I want to use the data stored in those lists but don't know how. In the program below I created 3 lists and I want to print it on the screen but it does not work:

k = 3
i = 1
L_1 = [1,2,3,4,5]
L_2 = [3,4,5,6,6]
L_3 = [6,7,1,5,2]

while True:

     print(L_[i]) #the error is here because I don't know how to recall the list
     i =i + 1
     if i == k:
          break

PS: It would be easier to write in this case print(L_1), print(L_2), print(L_3) but in the real program I am working on you can never know how many lists the user is going to create.

Thank you very much in advanced

  • You need a nested list, or dictionary – whackamadoodle3000 Jun 27 '18 at 18:26
  • 2
    If you want to iterate over a bunch of things, don't store them as separate variables; store them in a single variable as a list, tuple, dict, whatever. For example: `Ls = [[1,2,3,4,5], [3,4,5,6,6], [6,7,1,5,2]]`. Then you can just do `for L in Ls:`. – abarnert Jun 27 '18 at 18:26
  • `list_name = 'L_{}'.format(i)` and then, `print(locals()[list_name])` – DEEPAK SURANA Jun 27 '18 at 18:27
  • 1
    @DEEPAKSURANA That's almost always a bad idea. So you shouldn't suggest it to novices, except after explaining why it's almost always a bad idea and how to figure out if you have one of the rare exceptions where it's worth doing. (See some of the answers to the linked duplicates that do that.) – abarnert Jun 27 '18 at 18:28
  • Thank you very much for your quick support! I think I am going to redesign the program and use nested list and avoid globals – Archaeopteryx Psilocybin Jun 27 '18 at 18:45

0 Answers0