I want to create a list of variable length containing empty directories.
n = 10 # size of list
foo = []
for _ in range(n)
foo.append({})
Would you do this the same way, or is there something like?
a = [{}*n]
Method #1 : Using {} + "*" operator We can create a list containing single empty dictionary and then multiply it by Number that is size of list. The drawback is that similar reference dictionaries will be made which will point to similar memory location.
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.
One way to initialize a Dictionary<TKey,TValue>, or any collection whose Add method takes multiple parameters, is to enclose each set of parameters in braces as shown in the following example. Another option is to use an index initializer, also shown in the following example.
List comprehensions to the rescue!
foo = [{} for _ in range(n)]
There is no shorter notation, I am afraid. In Python 2 you use xrange(n)
instead of range(n)
to avoid materializing a useless list.
The alternative, [{}] * n
creates a list of length n
with only one dictionary, referenced n
times. This leads to nasty surprises when adding keys to the dictionary.
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