I need to incrementally fill a list or a tuple of lists. Something that looks like this:
result = []
firstTime = True
for i in range(x):
for j in someListOfElements:
if firstTime:
result.append([f(j)])
else:
result[i].append(j)
In order to make it less verbose an more elegant, I thought I will preallocate a list of empty lists
result = createListOfEmptyLists(x)
for i in range(x):
for j in someListOfElements:
result[i].append(j)
The preallocation part isn't obvious to me. When I do result = [[]] * x
, I receive a list of x
references to the same list, so that the output of the following
result[0].append(10)
print result
is:
[[10], [10], [10], [10], [10], [10], [10], [10], [10], [10]]
I can use a loop (result = [[] for i in range(x)]
), but I wonder whether a "loopless" solution exists.
Is the only way to get what I'm looking for