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!
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
ie
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.
You are printing a string literal (ie 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)
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)))
the issue with your code that you print a string not the 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)
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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.