The Wayback Machine - https://web.archive.org/web/20230118033041/https://www.geeksforgeeks.org/python-initialize-list-with-empty-dictionaries/
Skip to content
Related Articles

Related Articles

Python | Initialize list with empty dictionaries

Improve Article
Save Article
  • Last Updated : 17 Jan, 2023
Improve Article
Save Article

While working with Python, we can have a problem in which we need to initialize a list of a particular size with empty dictionaries. This task has it’s utility in web development to store records. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using {} + “*” operator This task can be performed using the “*” 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. 

Python3




# Python3 code to demonstrate working of
# Initialize list with empty dictionaries
# using {} + "*" operator
 
# Initialize list with empty dictionaries
# using {} + "*" operator
res = [{}] * 6
 
print("The list of empty dictionaries is : " + str(res))

Output : 

The list of empty dictionaries is : [{}, {}, {}, {}, {}, {}]

  Method #2 : Using {} + list comprehension This is perhaps the better and correct way to perform this task. We initialize the each index of list with dictionary, this way, we have independently referring dictionaries and don’t point to single reference. 

Python3




# Python3 code to demonstrate working of
# Initialize list with empty dictionaries
# using {} + list comprehension
 
# Initialize list with empty dictionaries
# using {} + "*" operator
res = [{} for sub in range(6)]
 
print("The list of empty dictionaries is : " + str(res))

Output : 

The list of empty dictionaries is : [{}, {}, {}, {}, {}, {}]

  Method #3 : Using itertools

Here is an example of how to use the itertools.repeat() method to initialize a list with empty dictionaries:

Python3




import itertools
 
def init_list_dict(n):
    # using itertools.repeat to repeat the empty dictionary n times
    return list(itertools.repeat({}, n))
 
res = init_list_dict(6)
print("The list of empty dictionaries is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy

Output

The list of empty dictionaries is : [{}, {}, {}, {}, {}, {}]

This method uses the itertools.repeat() function to repeat the empty dictionary, {} n times and creates a list out of it. This way we can create a list of n empty dictionaries.
This method also creates a new list and assigns it to the variable, so it is not the same as the first two examples.
The time complexity of this method is O(n) and space complexity is O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!