Casey Matczak
Casey Matczak

Reputation: 9

issue with accessing a variable in a list of tuples in python

This list of tuples is passed to the class on instantiation, which is when the class is created or the initializer is called. Getting TypeError: '>=' not supported between instances of 'tuple' and 'int'error. Help! I'm relatively new to this and can't figure it out!

class MedReport:
    def __init__(self,patients):
        self.patientname = patients[0]
        self.serum = patients[1]
       

    def reports(self):
        patientList = self.__dict__.values()
        index = 0
        
        for patients in patientList:
            if self.serum >= 80:
                print(self.patientname[index] + " has a heightened serum level")
            elif ((self.serum[index] > 40) and (self.serum[index] < 79)):
                print(self.patientname[index] + " has a moderate risk for infections")
            else:
                print(self.patientname[index] + " does not have a risk factor")
        index += 1

patients = [("John Blake", 22),("Jane Smith", 35),("Henry Baker", 77),("Thomas Cooper", 87)]

data = MedReport(patients)
data.reports()

Upvotes: 0

Views: 40

Answers (2)

Barmar
Barmar

Reputation: 781096

It seems like you expected patients[0] to return a list of all the [0] elements (the names) of the list of tuples, and patients[1] to return all the [1] elements. Indexing is not automatically distributed over list elements like that -- it's just indexing the list itself. As a result, you're setting self.patientname to the tuple ("John Blake", 22), and self.serum to the tuple ("Jane Smith", 35).

What you should do is save the entire patients list in an attribute, then extract the components when you loop over it.

class MedReport:
    def __init__(self,patients):
        self.patientlist = patients

    def reports(self):
        for index, (patientname, serum) in enumerate(self.patientlist):
            if serum >= 80:
                print(patientname + " has a heightened serum level")
            elif 40 < serum < 79
                print(patientname + " has a moderate risk for infections")
            else:
                print(patientname + " does not have a risk factor")

patients = [("John Blake", 22),("Jane Smith", 35),("Henry Baker", 77),("Thomas Cooper", 87)]

data = MedReport(patients)
data.reports()

Upvotes: 2

NoName69
NoName69

Reputation: 182

You are comparing a tuple to an integer. When you execute this self.serum = patients[1], you aren't getting an integer value, but instead a tuple.

Example: self.serum = patients[1] is retrieving this: ("Jane Smith", 35) To retrieve the integer inside the tuple you have to do this: self.serum = patients[#index][0]

Upvotes: 0

Related Questions