Is An Element of a Sequence an Object?

Erik python at lucidity.plus.com
Sat Jun 3 20:57:45 EDT 2017


On 04/06/17 00:42, Jon Forrest wrote:
> On 6/3/2017 12:38 PM, Thomas Jollans wrote:
> 
>  >> 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?
>  >
>  > No, strings don't internally store the characters as objects, and yes,
>  > the slicing operation creates objects. However, strings *are* sequences,
>  > sequences *are* ordered collections of objects.
> 
> I don't see how both can be true. "Object" has a clear meaning in
> Python, and the contents of a sequence don't meet the requirements,
> as I understand them.
> 
> If there were some way of measuring the number of objects in
> a program, then it would be easy to prove (or disprove) my hypothesis.
> In other words this program

You are confusing how a sequence might be implemented with how it can be 
thought of conceptually (*). I guess the book is explaining the 
conceptual model (which, as a book for learners, seems quite reasonable).

Whenever you extract an element from a sequence (whether that is by 
iteration - such as "for item in seq:" - or by indexing - such as 
"seq[x]") - you receive an object.

That doesn't mean that the sequence holds all of its elements physically 
in RAM as separate objects.

It is up to the sequence (which is also an object ;)) to decide how to 
implement iteration and indexing. It might do that by creating and 
storing a whole lot of real objects in RAM or it might do it by 
remembering the _formula_ for the sequence and creating those objects as 
and when they are asked for.

A list is an example of the first type (the list class doesn't know what 
heterogeneous objects might be appended to an instance, so it has to 
store an array of objects somehow).

The object returned by range() (xrange() in Py2) is an example of the 
latter - the "sequence" is actually just a clever object which knows how 
to calculate and create efficiently an object for one of its elements 
when you ask for it.

Hope that helps,
E.

(*) And that's great - you're actually thinking about this harder than a 
lot of people would. For a lot of learners the _conceptual_ model is 
good enough and that's all they'll ever need to understand. You are 
curious about the _implementation_ and that's good because now you'll 
see much more easily later how to program efficient sequence classes.



More information about the Python-list mailing list