Is An Element of a Sequence an Object?

Thomas Jollans tjol at tjol.eu
Sat Jun 3 15:38:03 EDT 2017


On 03/06/17 21:10, 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.
> 
> 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.
> 
> 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.

The sentence "A sequence is an ordered collection of objects" means that
a sequence has (ordered) elements, you can access these elements, and
when you do that, you will get an object (seeing as everything is an
object).

It does *not* imply that all the elements of a sequence exist in memory
before you access them. This definition of a sequence describes the
behaviour, not the implementation, of a sequence object.

Another built-in sequence type that doesn't bother to store all of its
elements as objects, or at all, is range:

>>> r = range(1000000000) # Does NOT create one billion objects
>>> i = r[10000] # The element is an object.
>>> i
10000
>>> id(i)
139758670321552
>>> i is 10000
False
>>>

NB: in Python 2, range does store all of its elements as objects.
Running this code in Python 2 will consume many gigabytes of memory. If
you have to use Python 2, use xrange instead.

Hope this helps.

Thomas



More information about the Python-list mailing list