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
You can initialize an empty tuple by having () with no values in them. You can also initialize an empty tuple by using the tuple function. A tuple with values can be initialized by making a sequence of values separated by commas.
You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.
We can create a list of tuples i.e. the elements of the tuple can be enclosed in a list and thus will follow the characteristics in a similar manner as of a Python list. Since, Python Tuples utilize less amount of space, creating a list of tuples would be more useful in every aspect.
result = [list(someListOfElements) for _ in xrange(x)]
This will make x distinct lists, each with a copy of someListOfElements
list (each item in that list is by reference, but the list its in is a copy).
If it makes more sense, consider using copy.deepcopy(someListOfElements)
Generators and list comprehensions and things are considered quite pythonic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With