List Comprehension Python -


this background code question:

class courselist(object):      def __init__(self, number):         self.number = number         self.students = []         print('in constructor of course list.')     def addstudent(self, who):         if not who.isstudent():             raise typeerror('not student')         if in self.students:             raise valueerror('duplicate student')         self.students.append(who)     def remstudent(self, who):         try:             self.students.remove(who)         except:             print (str(who) + ' not in ' + self.number)     def allstudents(self):         return self.students          #for s in self.students:             #yield s             #print (s)     def ugs(self):         indx = 0         while indx < len(self.students):             if type(self.students[indx]) == ug:                 yield self.students[indx]             indx += 1   sixhundred = courselist('6.00')   sixhundred.addstudent(ug1)  sixhundred.addstudent(g1)  sixhundred.addstudent(ug2) 

code1:

for x in sixhundred.allstudents():      print(x.__str__()) 

output:

jane doe mitch peabody john doe 

code2

print( (x.__str__() x in sixhundred.allstudents() ) ) 

output:

generator object genexpr @ 0x000000000448c048 

question: why print statement list comprehension(code 2) not work? doing wrong?

list comprehension round braces creates generator have in result. should use square brackets instead:

print([x.str() x in sixhundred.allstudents()]) 

and if want same result in code 1, type:

print(' '.join([x.str() x in sixhundred.allstudents()])) 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -