Create a list of empty dictionaries

I want to create a variable-length list containing empty directories.

n = 10 # size of list foo = [] for _ in range(n) foo.append({}) 

Would you do it the same way, or is there something like that?

 a = [{}*n] 
+8
python dictionary list
source share
1 answer

List the understanding of salvation!

 foo = [{} for _ in range(n)] 

I am not afraid of short notes. In Python 2, you use xrange(n) instead of range(n) to avoid materializing a useless list.

Alternative [{}] * n creates a list of length n with only one dictionary referenced n times. This leads to unpleasant surprises when adding keys to the dictionary.

+23
source share

All Articles