2

If I have pre-set list variables that are the same name except for they end in a different number, how can I create variables in a for loop that will call those lists?

My issue is that the variable I create in the for loop is staying as a string. I need it to recognize that it's simply a name of a variable.

Example:

list1 = [2, 4, 3, 7]
list2 = [4, 5, 6]
list3 = [9, 5, 7, 8, 3, 2, 1]
list4 = [4, 1]

for i in range(1,5):
    print ("list%d" % (i))

This results in printing the strings:

list1

list2

list3

list4

I want it to print out the actual lists.

Thanks for any help!

Sociopath
  • 13,068
  • 19
  • 47
  • 75
AmericanMade
  • 453
  • 1
  • 9
  • 22

4 Answers4

6

You can achieve below as by using 'eval'.

list1 = [2, 4, 3, 7]
list2 = [4, 5, 6]
list3 = [9, 5, 7, 8, 3, 2, 1]
list4 = [4, 1]

for i in range(1,5):
    print (eval('list%d'% (i)))

But as mentioned in comments, this is not recommended. You should rewrite by dict or list of list i.e.

my_list = [[2, 4, 3, 7],
           [4, 5, 6],
           [9, 5, 7, 8, 3, 2, 1],
           [4, 1]]

for i in range(len(my_list)):
    print (my_list[i])

Note that i change the name of variable list to my_list because the word list is a reserved word.

takoika
  • 363
  • 2
  • 10
3

You are printing a string literal (i.e. plain text) not the actual variable of each list. One thing you can do is put those lists in a class or a dictionary.

Assuming it's a class:

class cls:
    list1 = [2, 4, 3, 7]
    list2 = [4, 5, 6]
    list3 = [9, 5, 7, 8, 3, 2, 1]
    list4 = [4, 1]


for i in range(1, 5):
    print getattr(cls, 'list{}'.format(i))

Assuming it's a dictionary:

lists = {
    'list1': [2, 4, 3, 7],
    'list2': [4, 5, 6],
    'list3': [9, 5, 7, 8, 3, 2, 1],
    'list4': [4, 1],
}

for k, v in lists.items():
    print '{0}={1}'.format(k, v)
fips
  • 4,319
  • 5
  • 26
  • 42
2

As suggested in the comments you should consider some other data structue to use here.

If you still want this to work. You may try as below

for i in range(1,5):
    print (eval("list"+str(i)))
Ashish
  • 266
  • 2
  • 9
2

the issue with your code that you print a string not the list variable

to loop through a list variable

list1 = [2, 4, 3, 7]
list2 = [4, 5, 6]
list3 = [9, 5, 7, 8, 3, 2, 1]
list4 = [4, 1]

for i in list1:
    print (i)

or you can put all the lists in a list and loop through it

new_list=[[2, 4, 3, 7],[4, 5, 6],[9, 5, 7, 8, 3, 2, 1],[4, 1]]

for e in new_list:
    print(e)

you can also put all of them in a dictionary structure {key,value}

dic_of_lists={"list1":[2, 4, 3, 7],"list2":[4, 5, 6]
          ,"list3":[9, 5, 7, 8, 3, 2, 1],"list4":[4, 1]}

#to loop through the dictionary
for key,value in dic_of_lists.items():
    print(key+" : ")
    print(value)