Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generator vs Sequence object

Tags:

python

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?

like image 216
MoiTux Avatar asked Jun 30 '14 22:06

MoiTux


1 Answers

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,

  • something is a sequence if it supports all of the methods defined in that link.
  • If it's a generator, it probably only supports a couple methods (.next or .__next__ are the most important)1.
  • there's also an in-between land which is "iterable" -- "iterables" have a typically2 defined __iter__ method which returns "generator" (something with a well defined .next or .__next__3 method)
  • just to be complete, you'll often see people say "iterators" which are very similar to generators (implement __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

like image 69
mgilson Avatar answered Sep 28 '22 16:09

mgilson