I know the difference between range and xrange.
But I was surprised to see that xrange wasn't agenerator but a sequence object.
What's the difference then, how to create a sequence object and when used it over a generator?
The reason that xrange is a sequence object is because it supports the sequence methods interface. For example you can index it (which is something you can't do with a vanilla generator):
print xrange(30)[5] # No Error
In other words,
.next or .__next__ are the most important)1. __iter__ method which returns "generator" (something with a well defined .next or .__next__3 method)__iter__ which returns the object itself and has a well defined next and/or __next__ method).More formal definitions can be found in the documentation glossary
1generators also support __iter__ and simply return themselves. so techincally, all generators are also iterables (and iterators!), but not all iterables (iterators) are generators.
2__len__ + __getitem__ is enough to create an iterable as pointed out in the comments.
3__next__ is the method name for python3.x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With