-1

I have the following variables:

info0=["info01","info02","info03","info04",]
info1=["info11","info12","info13","info14",]
info2=["info21","info22","info23","info24",]
info3=["info31","info32","info33","info34",]
info4=["info41","info42","info43","info44",]
info5=["info51","info52","info53","info54",]

and I have the following function that prints the elements of a list:

def printelements(list_of_i):
    for element in list_of_i:
        print(element)

so I want to create a loop to go thought all the lists above and print all the elements:

for i in range(0,5):
    printelements(info(i)) <-- so the function should change based on the i, in order to print all the lists

How can I do the above? I know alternative ways to print the lists, but I want to focus on the variable to change based on the i.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
stavros_p
  • 13
  • 3

3 Answers3

0

no need for a function here since you probably wont reuse it and it doesnt really minimize code

[[print(i) for i in lst] for lst in [info0,info1,info2,info3,info4,info5]]
Ironkey
  • 2,568
  • 1
  • 8
  • 30
0

Well for starters I would recommend just having a list of info.

for info in [info0, info1, info2, info3, info4]:
    printelements(info)

You might also be able to do something with the eval() command, but I wouldn't recommend it.

for i in range(5):
    printelements(eval("info{}".format(i)))

However, using this would be such bad practice that I'm not even sure if it will work. It is such bad practice to use eval() in this way that I have never tried code like this. I'm just bringing it up for the sake of argument.

Locke
  • 7,626
  • 2
  • 21
  • 41
0

The trick is not to figure out how to compute variable names on the fly, but instead to add another layer of list. A list of lists.

Rule of thumb: Any time you have variable names with numbers attached you should probably be using a list.

info = [
    ["info01","info02","info03","info04",],
    ["info11","info12","info13","info14",],
    ["info21","info22","info23","info24",],
    ["info31","info32","info33","info34",],
    ["info41","info42","info43","info44",],
    ["info51","info52","info53","info54",],
]

for i in range(0,5):
    printelements(info[i])

You can also get rid of i and loop over the sublists directly:

for sublist in info:
    printelements(sublist)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578