Is An Element of a Sequence an Object?
Akira Li
4kir4.1i at gmail.com
Sun Jun 4 08:22:21 EDT 2017
Jon Forrest <nobozo at gmail.com> writes:
> I'm learning about Python. A book I'm reading about it
> says "...
> a string in Python is a sequence.
correct.
> A sequence is an ordered collection of objects".
correct. https://docs.python.org/3/glossary.html#term-sequence
> This implies that each character in a string
> is itself an object.
Everything in Python is an object. If *s* is a name that refers to a str
object then *s[i]* returns i-th Unicode code point from the string as a
str object of length 1:
>>> s = "ab"
>>> s[0]
'a'
It does not matter how *s* is represented internally on a chosen Python
implementation: *s[0]* may return an existing object or it may create a
new one on-the-fly.
Here's a perfectly valid sequence of ten squares:
>>> class Squares:
... def __getitem__(self, i):
... if not (-len(self) <= i < len(self)):
... raise IndexError(i)
... if i < 0:
... i += len(self)
... return i * i
...
... def __len__(self):
... return 10
>>> s = Squares()
>>> s[9]
81
All 10 squares are generated on-the-fly (though all int objects already
exist due to the small int caching on CPython).
More information about the Python-list
mailing list