Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Initialize dictionary with multiple keys
Next article icon

Python | Initialize list with empty dictionaries

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 : [{}, {}, {}, {}, {}, {}]

The time complexity of this code is O(1) as it only involves creating a list of empty dictionaries of a fixed size, which does not depend on the input size.

The auxiliary space complexity of this code is O(n), where n is the size of the list.

  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 : [{}, {}, {}, {}, {}, {}]

Time Complexity: O(n) where n is the number of elements in the list 
Auxiliary Space: O(n), where n is the number of elements in the new res list 

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)

Method #4: Using a for loop to append empty dictionaries to the list

This program initializes a list containing n empty dictionaries using a for loop and appends an empty dictionary to the list in each iteration. Finally, it prints the resulting list of dictionaries.

Python3




# Initialize list with empty dictionaries using a for loop
n = 6
res = []
for i in range(n):
    res.append({})
print("The list of empty dictionaries is : " + str(res))
 
 
Output
The list of empty dictionaries is : [{}, {}, {}, {}, {}, {}]

Time complexity: O(n)
Auxiliary space complexity: O(n)

Method #5: Using list comprehension with range function

This will create a list of 6 empty dictionaries using list comprehension with the range function. The _ is used as a placeholder variable as it is not used in the loop.

1-  Initialize an empty list called res
2-   Create a loop to iterate over a range of 6 (0 to 5) using _ as a placeholder variable
For each iteration of the loop, create an empty dictionary using {}
3-  Append the empty dictionary to the list res
4-  Print the string “The list of empty dictionaries is: ” along with the value of res converted to a string         using the str() function
5-  Repeat steps 2-5 for a total of 9 times

Python3




res = [{} for _ in range(6)]
print("The list of empty dictionaries is: " + str(res))
 
 
Output
The list of empty dictionaries is: [{}, {}, {}, {}, {}, {}]

Time complexity: O(n), where n is the number of dictionaries in the list, because it is a simple loop through the range function.
Auxiliary space: O(n), as it creates a list of n empty dictionaries in memory.

Method #6: Using the built-in function dict() inside a loop to initialize the list with empty dictionaries.

This method creates a list of 6 empty dictionaries using the dict() function inside a list comprehension. Each iteration of the loop creates a new empty dictionary object, which is then added to the list. This method is more explicit and easier to read than using the {} + ‘*’ operator or list comprehension.

Python3




# Initialize list with empty dictionaries using dict() function
res = [dict() for i in range(6)]
 
print("The list of empty dictionaries is : " + str(res))
 
 
Output
The list of empty dictionaries is : [{}, {}, {}, {}, {}, {}]

The time complexity of the above code is O(n), where n is the number of elements in the list. 

The space complexity of this code is also O(n), where n is the number of elements in the list.



Next Article
Python | Initialize dictionary with multiple keys
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Initialize dictionary keys with Matrix
    Sometimes, while working with Python Data, we can have a problem in which we need to construct an empty mesh of dictionaries for further population of data. This problem can have applications in many domains which include data manipulation. Let's discuss certain ways in which this task can be perfor
    4 min read
  • Python - Initialize dictionary with custom value list
    In python one usually comes across situations in which one has to use dictionary for storing the lists. But in those cases, one usually checks for first element and then creates a list corresponding to key when it comes. But its always wanted a method to initialize the dict. keys with a custom list.
    4 min read
  • Python | Initializing dictionary with list index-values
    While working with Python we might need to perform tasks in which we need to assign a dictionary with list values as dictionary values and index as dictionary keys. This type of problem is quite common in cases we need to perform data-type conversion. Let's discuss certain ways in which this task ca
    4 min read
  • Python | Initialize dictionary with multiple keys
    Sometimes, while working with dictionaries, we might have a problem in which we need to initialize the dictionary with more than one key with the same value. This application requirement can be in domains of web development in which we might want to declare and initialize simultaneously. Let's discu
    8 min read
  • Python | Initializing dictionary with list index values
    While working with dictionaries, we might come across a problem in which we require to attach each value in list with it's index, to be used afterwards to solve question. This technique is usually very useful in competitive programming domain. Let's discuss certain ways in which this task can be per
    5 min read
  • Initialize a Dictionary with Only Keys from a List - Python
    The task of initializing a dictionary with only keys from a list in Python involves creating a dictionary where the keys are derived from the elements of the list and each key is assigned a default value . For example, given a list like ["A", "B", "C"], the goal is to transform this list into a dict
    3 min read
  • Python | Initialize dictionary with None values
    Sometimes, while working with dictionaries, we might have a utility in which we need to initialize a dictionary with None values so that they can be altered later. This kind of application can occur in cases of memoization in general or competitive programming. Let's discuss certain ways in which th
    4 min read
  • Initialize Python Dictionary with Keys and Values
    In this article, we will explore various methods for initializing Python dictionaries with keys and values. Initializing a dictionary is a fundamental operation in Python, and understanding different approaches can enhance your coding efficiency. We will discuss common techniques used to initialize
    3 min read
  • Python - Extract dictionary items with List elements
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the items from dictionary that constitute all the elements from a list. This kind of problem can occur in domains such as competitive programming and web development. Let's discuss certain ways i
    8 min read
  • Python | Initialize dictionary with common value
    While working with Python, sometimes, we might have a problem in which we require the initialize the static list into a dictionary with a constant value. Let's discuss certain ways in which this task can be performed. Method #1: Using dict() + list comprehension The combination of above functions ca
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences