Reputation: 91
I need 20 empty lists with the letters from a to t.My code right now is:
list_a = []
list_b = []
list_c = []
...
creates me this:
list_a[]
list_b[]
list_c[]
...
can i do this with a simple for loop somehow?? This is what i have right now. I can loop the letters from a to t and print them out
for i in range(ord('a'), ord('t') +1):
print i
output:
a
b
c
d
e
...
and so on...
I need it for that script i wrote.I have 2 empty lists for testing.It's working fine .But now i need to play with 20 lists
from os import system
list_a = []
list_b = []
list_c = [1, 2, 3, 4, 5]
while True:
system("clear")
print "\nList A ---> ", list_a
print "List B ---> ", list_b
print "List C ---> ", list_c
item = input ("\n?> ")
place = [list_a, list_b, list_c]
place_name = ["List A", "List B", "List C"]
for i ,a in zip(place, place_name):
if item in i:
print "\nItem", item, "--->", a
print "\n\n1) List A"
print "2) List B"
print "3) List C\n"
target = input("move to ---> ")
target = target - 1
target = place[target]
i.remove(item)
target.append(item)
print "\nItem moved"
break
raw_input()
Upvotes: 1
Views: 1232
Reputation: 5530
You can use exec to interpret generated code.
for i in xrange(ord('a'),ord('t')+1):
exec("list_%c=[]" % i)
print locals()
exec should not be overused, but here it seems to fit well.
Upvotes: 1
Reputation: 2277
Use locals()
function
>>> names = locals()
>>> for i in xrange(ord('c'), ord('t')+1):
>>> names['list_%c' % i] = []
>>> list_k
[]
Upvotes: 1
Reputation: 1736
You can make a list of lists like this my_list = [[] for i in range (20)]
.
If you want to use a for-loop, i.e. not using python's awesome list-comprehension, then you can do so as follows:
my_list = []
for i in range (20):
my_list.append ([])
Upvotes: 1
Reputation: 336408
Use a different approach:
mylist = {letter:[] for letter in "abcdefghijklmnopqrst"}
Now you can access mylist["a"]
through mylist["t"]
Upvotes: 5