InStringsandTupleswe noted thatstringandtupleobjects are immutable. They cannot be changed once they are created. Programmers experienced in other languages sometimes find this to be an odd restriction. Two common questions that arise are how to expand astringand how to remove characters from astring. Generally, we don’t expand or contract astring, we create a newstringthat is the concatenation of the originalstringobjects. For example:
>>> a="abc"
>>> a=a+"def"
>>> a 'abcdef'
In effect, Python gives usstringobjects of arbitrary size. It does this by dynamically creating a newstring instead of modifying an existingstring.
Some programmers who have extensive experience in other languages will ask if creating a new string from the original string is the most efficient way to accomplish this. Or they suggest that it would be
“simpler” to allow a mutable string for this kind of concatenation. The short answer is that Python’s storage management makes this use of immutablestringthe simplest and most efficient.
Responses to the immutability of tuple and mutability of list vary, including some of the following fre- quently asked questions.
Since alist does everything atuple does and is mutable, why bother withtuple?
Immutable tuple objects are more efficient than variable-length list objects for some operations. Once
thetupleis created, it can only be examined. When it is no longer referenced, the normal Python garbage
collection will release the storage for thetuple.
Most importantly, a tuple can be reliably hashed to a single value. This makes it a usable key for a mapping. Many applications rely on fixed-length tuples. A program that works with coordinate geometry in two dimensions may use 2-tuples to represent (x, y) coordinate pairs. Another example might be a program that works with colors as 3-tuples, (r, g, b), of red, green and blue levels. A variable-length list is not appropriate for these kinds of fixed-length tuple.
Wouldn’t it be “more efficient” to allow mutablestrings?
There are a number of axes for efficiency: the two most common are time and memory use.
A mutablestring could use less memory. However, this is only true in the benign special case where we are only replacing or shrinking the string within a fixed-size buffer. If the string expands beyond the size of the buffer the program must either crash with an exception, or it must switch to dynamic memory allocation. Python simply uses dynamic memory allocation from the start. C programs often have serious security problems created by attempting to access memory outside of astring buffer. Python avoids this problem by using dynamic allocation of immutablestringobjects.
Processing a mutable string could use less time. In the cases of changing a stringin place or removing characters from astring, a fixed-length buffer would require somewhat less memory management overhead. Rather than indict Python for offering immutable string, this leads to some productive thinking about stringprocessing in general.
In text-intensive applications we may want to avoid creating separatestringobjects. Instead, we may want to create a singlestringobject – the input buffer – and work with slices of that buffer. Rather than create string, we can createsliceobjects that describe starting and ending offsets within the one-and-only input buffer.
If we then need to manipulate these slices of the input buffer, we can create new string objects only as needed. In this case, our application program is designed for efficiency. We use the Pythonstringobjects when we want flexibility and simplicity.
FOURTEEN
TUPLES
We’ll look attuplefrom a number of viewpoints: semantics, literal values, operations, comparison operators, statements, built-in functions and methods.Additionally, we have a digression on theΣoperator inDigression on The Sigma Operator.
14.1 Tuple Semantics
A tuple is a container for a fixed sequence of data objects. The name comes from the Latin suffix for
multiples: double, triple, quadruple, quintuple.
Mathematicians commonly considerordered pairs; for instance, most analytical geometry is done with Carte- sian coordinates (x,y ). An ordered pair can be generalized as a 2-tuple.
An essential ingredient here is that atuplehas a fixed and known number of elements. A 3-dimensional point is a 3-tuple. An CMYK color code is a 4-tuple. The size of thetuple can’t change without fundamentally redefining the problem we’re solving.
Atuple is an immutable sequence of Python objects. Since it is a sequence, all of the common operations
to sequences apply. Since it is immutable, it cannot be changed. Two common questions that arise are how to expand atupleand how to remove objects from atuple.
When someone asks about changing an element inside atuple, either adding, removing or updating, we have to remind them that thelist, covered inLists, is for dynamic sequences of elements. Atupleis generally applied when the number of elements is fixed by the nature of the problem.
This tuple processing even pervades the way functions are defined. We can have positional parameters
collected into atuple, something we’ll cover in Advanced Parameter Handling For Functions.