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:
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.
Now that I understand how his solution works, I'm curious how this is advantageous to the other for-loop. Thanks
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.
Join our real-time social learning platform and learn together with your friends!