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:
Create a List of Strings in Python
Next article icon

Create Class Objects Using Loops in Python

Last Updated : 07 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a task to create Class Objects using for loops in Python and return the result, In this article we will see how to create class Objects by using for loops in Python.

Example:

Input: person_attributes = [("Alice", 25), ("Bob", 30), ("Charlie", 35)]
Output: Name: Alice, Age: 25, Name: Bob, Age: 30, Name: Charlie, Age: 35
Explanation: Class objects are created using loop

Create Class Objects Using Loops in Python

Below are some examples of create Class Objects in Python:

Example 1: Simple Class Instantiation Using For Loops

in this example, below code defines a `Person` class, creates instances with a for loop using attributes from a list of tuples, and prints each person's details. It showcases a compact and efficient use of for loops in Python for object instantiation and data handling.

Python3
class Person:     def __init__(self, name, age):         self.name = name         self.age = age  # List of tuples containing person attributes person_attributes = [("Alice", 25), ("Bob", 30), ("Charlie", 35)]  # Create Person objects using a for loop people = [] for name, age in person_attributes:     person = Person(name, age)     people.append(person)  # Print the details of each person for person in people:     print(f"Name: {person.name}, Age: {person.age}") 

Output
Name: Alice, Age: 25 Name: Bob, Age: 30 Name: Charlie, Age: 35 

Output

Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35

Example 2: Dynamic Object Creation From List of Attributes Using For Loop

In this example, below code defines a `Product` class and utilizes a list of dictionaries to create instances with concise list comprehension. The for loop then prints the details of each product, illustrating an efficient and readable approach to object instantiation and data handling in Python.

Python3
class Product:     def __init__(self, name, price):         self.name = name         self.price = price  # List of dictionaries containing product attributes product_data = [     {"name": "Laptop", "price": 1000},     {"name": "Phone", "price": 800},     {"name": "Tablet", "price": 500} ]  # Create Product objects using list comprehension products = [Product(data["name"], data["price"]) for data in product_data]  # Print the details of each product for product in products:     print(f"Product: {product.name}, Price: ${product.price}") 

Output
Product: Laptop, Price: $1000 Product: Phone, Price: $800 Product: Tablet, Price: $500 

Example 3: Using Dictionaries to Create Objects Using For loop

In this example, below code introduces two classes, `Product` and `Person`, with specific attributes. Using for loops, it efficiently creates instances for each class from different data structures (dictionaries and tuples) and prints their details. This concise approach highlights the flexibility of for loops in handling various class instantiation scenarios in Python.

Python3
class Product:     def __init__(self, name, price):         self.name = name         self.price = price  class Person:     def __init__(self, name, age):         self.name = name         self.age = age  product_data = [     {"name": "Laptop", "price": 1000},     {"name": "Phone", "price": 800},     {"name": "Tablet", "price": 500} ]  products = [] for data in product_data:     product = Product(**data)     products.append(product)  for product in products:     print(f"Product: {product.name}, Price: ${product.price}")  person_attributes = [("Alice", 25), ("Bob", 30), ("Charlie", 35)]  people = [Person(*attributes) for attributes in person_attributes]  for person in people:     print(f"Name: {person.name}, Age: {person.age}") 

Output
Product: Laptop, Price: $1000 Product: Phone, Price: $800 Product: Tablet, Price: $500 Name: Alice, Age: 25 Name: Bob, Age: 30 Name: Charlie, Age: 35 

Conclusion

In conclusion , Utilizing for loops to create class objects in Python is a powerful technique that enhances code efficiency, scalability, and flexibility. By iterating through collections of data, you can dynamically generate instances of a class with minimal code duplication. This approach not only makes your code more readable but also simplifies maintenance and updates. The for loop proves to be a valuable tool in the realm of object-oriented programming, empowering developers to handle repetitive tasks with elegance and precision.


Next Article
Create a List of Strings in Python

K

kishankaushik
Improve
Article Tags :
  • Python
  • Python Programs
  • python-basics
  • python-oop-concepts
Practice Tags :
  • python

Similar Reads

  • Create a List of Strings in Python
    Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
    3 min read
  • Python - Create list of tuples using for loop
    In this article, we will discuss how to create a List of Tuples using for loop in Python. Let's suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index. Method 1: Using For loop with append
    2 min read
  • Creating a List of Sets in Python
    Creating a list of sets in Python involves storing multiple sets within list structure. Each set can contain unique elements and the list can hold as many sets as needed. In this article, we will see how to create a list of set using different methods in Python. Using List ComprehensionList comprehe
    2 min read
  • How to Append Objects in a List in Python
    The simplest way to append an object in a list using append() method. This method adds an object to the end of the list. [GFGTABS] Python a = [1, 2, 3] #Using append method to add object at the end a.append(4) print(a) [/GFGTABS]Output[1, 2, 3, 4] Let's look into various other methods to append obje
    2 min read
  • Create A List of Lists Using For Loop
    In Python, creating a list of lists using a for loop involves iterating over a range or an existing iterable and appending lists to the main list. This approach allows for the dynamic generation of nested lists based on a specific pattern or condition, providing flexibility in list construction. In
    4 min read
  • Create Dynamic Dictionary using for Loop-Python
    The task of creating a dynamic dictionary using a for loop in Python involves iterating through a list of keys and assigning corresponding values dynamically. This method allows for flexibility in generating dictionaries where key-value pairs are added based on specific conditions or inputs during i
    4 min read
  • Python - Create List of Size n
    Creating a list of size n in Python can be done in several ways. The easiest and most efficient way to create a list of size n is by multiplying a list. This method works well if we want to fill the list with a default value, like 0 or None. [GFGTABS] Python # Size of the list n = 5 # Creating a lis
    2 min read
  • Convert Generator Object To String Python
    Generator objects in Python are powerful tools for lazy evaluation, allowing efficient memory usage. However, there are situations where it becomes necessary to convert a generator object to a string for further processing or display. In this article, we'll explore four different methods to achieve
    3 min read
  • Get User Input in Loop using Python
    In Python, for and while loops are used to iterate over a sequence of elements or to execute a block of code repeatedly. When it comes to user input, these loops can be used to prompt the user for input and process the input based on certain conditions. In this article, we will explore how to use fo
    3 min read
  • How to Create List of Dictionary in Python Using For Loop
    The task of creating a list of dictionaries in Python using a for loop involves iterating over a sequence of values and constructing a dictionary in each iteration. By using a for loop, we can assign values to keys dynamically and append the dictionaries to a list. For example, with a list of keys a
    3 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