Coder48
Coder48

Reputation: 41

How do I create objects from lists?

Suppose I have two lists, the first is named studentName

studentName = ["Jack","Simon","John","Matthew"]

And the second is named studentGrade

studentGrade = [100,88,74,94]

I also have a class named "Students"

class Students():
  def __init__(self,name,grade):
    self.name = name
    self.grade = grade

How do I create objects without using the usual method like this:

Jack = Students("Jack",100)

I want to do the same but without having to type 4 lines. Instead I want to use loops on the lists. Is this possible?

Upvotes: 1

Views: 64

Answers (1)

azro
azro

Reputation: 54148

You can do so using zip to iterate on both list at once; also I'd suggest you name your class Student at singular as it represents onlye one person, not multiple

studentName = ["Jack", "Simon", "John", "Matthew"]
studentGrade = [100, 88, 74, 94]
students = [Student(n, g) for n, g in zip(studentName, studentGrade)]

Add a __repr__ and you can see the results

class Students():
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade    
    def __repr__(self):
        return f"{self.name}:{self.grade}"

if __name__ == '__main__':
    studentName = ["Jack", "Simon", "John", "Matthew"]
    studentGrade = [100, 88, 74, 94]
    students = [Students(n, g) for n, g in zip(studentName, studentGrade)]
    print(students)  # [Jack:100, Simon:88, John:74, Matthew:94]

Upvotes: 5

Related Questions