Is An Element of a Sequence an Object?

Steve D'Aprano steve+python at pearwood.info
Sat Jun 3 20:23:49 EDT 2017


On Sun, 4 Jun 2017 05:10 am, Jon Forrest wrote:

> I'm learning about Python. A book I'm reading about it
> says "... a string in Python is a sequence. A sequence is an ordered
> collection of objects". This implies that each character in a string
> is itself an object.

Which book is this? Because its wrong.

A sequence in Python is:

    An iterable which supports efficient element access using 
    integer indices via the __getitem__() special method and 
    defines a __len__() method that returns the length of the
    sequence. Some built-in sequence types are list, str, tuple,
    and bytes. Note that dict also supports __getitem__() and 
    __len__(), but is considered a mapping rather than a sequence
    because the lookups use arbitrary immutable keys rather than
    integers.

    The collections.abc.Sequence abstract base class defines a much
    richer interface that goes beyond just __getitem__() and __len__(),
    adding count(), index(), __contains__(), and __reversed__().
    Types that implement this expanded interface can be registered
    explicitly using register().

https://docs.python.org/3/glossary.html#term-sequence


One way for an object to provide efficient element access is to store the
elements as objects, e.g. what lists and tuples do.

Another way is to calculate them on the fly, as range (xrange in Python 2) does.

A third way is to copy the elements out of some other data structure as needed,
as strings do, and array.array.

We can fix the book's statement by changing it to:

    A sequence is an ordered collection of *elements* ...

without specifying how the elements are stored (as Python objects, or as values
in some low-level data structure, or even virtual elements which are computed
on the fly as needed).


> This doesn't seem right to me, but since I'm just learning Python
> I questioned the author about this. He gave an example the displays
> the ids of string slices. These ids are all different, but I think
> that's because the slicing operation creates objects.

It does indeed.


> I'd like to suggest an explanation of what a sequence is
> that doesn't use the word 'object' because an object has
> a specific meaning in Python.
> 
> Am I on the right track here?

Absolutely.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list