Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 17 Online
OpenStudy (anonymous):

In the solution to Problem Set 2, why does the professor use this: for i in xrange(len(poly)): instead of simply this: for i in poly:

OpenStudy (rsmith6559):

len( poly ) returns an integer. So if poly had 6 things in it, i would have 6 values, 0 to 5. for i in poly: i would be poly[ 0 ], poly[ 1 ], poly[ 2 ].....poly[ 5 ] Instead of a series of numbers, it would be a series of whatever poly contains.

OpenStudy (anonymous):

Now that I understand how his solution works, I'm curious how this is advantageous to the other for-loop. Thanks

OpenStudy (rsmith6559):

The two advantages to his solution is that xrange is just an iterator, range creates an iterable object and iterates over it. The second advantage is that by using len( poly ), if poly's length changes, the loop adapts to that change instead of the programmer having to fix their code.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!