Generator vs Sequence Object

I know the difference between range and xrange .
But I was surprised to see that xrange not a generator , but << 24>.

What is the difference, how to create a sequence object and when using it over a generator ?

+8
python
source share
2 answers

The reason xrange is a sequence object is because it supports the sequence method interface . For example, you can index it (which you cannot do with the vanilla generator):

 print xrange(30)[5] # No Error 

In other words,

  • something is a sequence if it supports all the methods defined in this link.
  • If it's a generator, it probably only supports methods ( .next or .__next__ are the most important) 1 .
  • there is also an intermediate ground that is “iterable” - “iterability” have a typical 2 __iter__ method that returns a “generator” (something with a well-defined .next or .__next__ 3 )
  • just to be complete, you often see people say “iterators” that are very similar to generators (implement __iter__ , which returns the object itself and has a well-defined next and / or __next__ )).

More formal definitions can be found in the documentation glossary.

1 generators also support __iter__ and just return themselves. so technically, all generators are also iterators (iterators!), but not all iterators (iterators) are generators.
2 __len__ + __getitem__ enough to create iterability, as indicated in the comments.
3 __next__ is the method name for python3.x

+11
source share

A sequence object is a special, C-provided type. A generator can be written with user code.

This is a Python 2 thing - in Python 3:

 >>> print(type(range(1))) <class 'range'> >>> print(type(xrange(1))) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'xrange' is not defined 

python2:

 Python 2.7.5+ (default, Feb 27 2014, 19:37:08) [GCC 4.8.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print type(xrange(1)) <type 'xrange'> 
+2
source share

All Articles