Reputation: 63
I wish to create a new list each time a for loop runs
#Reading user input e.g. 10
lists = int(raw_input("How many lists do you want? "))
for p in range(0,pooled):
#Here I want to create 10 new empty lists: list1, list2, list3 ...
Is there any smart way of doing this?
Thanks,
Kasper
Upvotes: 5
Views: 77866
Reputation: 1888
To create our lists we generate names on the fly and assign them an empty list:
lists = int(input("How many lists do you want? "))
varname = 'list'
for i in range(lists):
exec(f"{varname}{i} = []")
exec(f'print(f"list{lists-1} is", list{lists-1})')
# list9 is []
Upvotes: 1
Reputation: 17173
perhaps in your situation you could use a defaultdict?
>>> from collections import defaultdict
>>> m=defaultdict(list)
>>> m
defaultdict(<type 'list'>, {})
>>> for i in range(5):
... len(m[i])
...
0
0
0
0
0
>>> m
defaultdict(<type 'list'>, {0: [], 1: [], 2: [], 3: [], 4: []})
Upvotes: 1
Reputation: 363487
Use a list comprehension:
num_lists = int(raw_input("How many lists do you want? "))
lists = [[] for i in xrange(num_lists)]
Upvotes: 8
Reputation: 10969
The easiest way is to create a list of lists:
num_lists = int(raw_input("How many lists do you want? "))
lists = []
for p in range(num_lists):
lists.append([])
Then you can access, for example, list 3 with list[2]
, and the ith item of list 3 with list[2][i]
.
Upvotes: 5