1

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?

Coder48
  • 41
  • 6
  • 1
    This is probably what you are looking for [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) – BurdenKing Feb 03 '21 at 21:57
  • Hi, as you have now answers now, you may think about [accepting an answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) to reward the one that gives you the most helpful comment. – azro Feb 13 '21 at 09:44

1 Answers1

5

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]
azro
  • 53,056
  • 7
  • 34
  • 70