memory management - How to create a list or tuple of empty lists in Python? -
i need incrementally fill list or tuple of lists. looks this:
result = [] firsttime = true in range(x): j in somelistofelements: if firsttime: result.append([f(j)]) else: result[i].append(j)
in order make less verbose more elegant, thought preallocate list of empty lists
result = createlistofemptylists(x) in range(x): j in somelistofelements: result[i].append(j)
the preallocation part isn't obvious me. when result = [[]] * x
, receive list of x
references same list, output of following
result[0].append(10) print result
is:
[[10], [10], [10], [10], [10], [10], [10], [10], [10], [10]]
i can use loop (result = [[] in range(x)]
), wonder whether "loopless" solution exists.
is way i'm looking
result = [list(somelistofelements) _ in xrange(x)]
this make x distinct lists, each copy of somelistofelements
list (each item in list reference, list in copy).
if makes more sense, consider using copy.deepcopy(somelistofelements)
generators , list comprehensions , things considered quite pythonic.
Comments
Post a Comment