Numbers and Strings

Python provides several numeric types and two string types. What all these types have in common is that they are immutable. This means that in Python, numbers and strings cannot be changed. This sounds rather limiting, but thanks to Python's augmented assignment operators (+=, *=, etc.), it simply is not a problem.

Before looking at the specific data types we will look at one important consequence of the immutability. Let us type some simple expressions into IDLE:

>>> x = 5 >>> y = x >>>x, y (5, 5)

Here we have created an object of type int with the value 5 and bound the name x to it. We have then assigned x to y which has the effect of binding y to the same object that x is bound to. So, when we print them in IDLE (in a program we would have to write print x, y, but in IDLE we just write an expression and IDLE automatically prints it), IDLE outputs the values as a Tuples tuple—essentially a read-only list of values. ^ 29

Now let us increment y:

We might have expected both x and y to have the value 6 since both referred to the same integer object. But because Python numbers (and strings) are immutable, this does not happen. The augmented assignment operators when applied to immutable objects are mere syntactic sugar: They do not change

Table 1.1 Python's Keywords*

and

class

elif

finally

if

lambda

print

while

as

continue

else

for

import

not

raise

with26

assert15

def

except

from

in

or

return

yield23

break

del

exec

global

is

pass

try

the objects they are applied to. So what really happened is this: y = y + 1, so a new integer object was created (with value 6), and y was bound to this new object. As a result, when we asked IDLE to print x and y, they were referring to different objects, each with a different value.

Shallow and Deep Copying sidebar

In practice, the immutability of numbers and strings is very convenient. For example:

>>> s = "Bath" >>>t = " Hat" >>> u = s >>> s += t >>> s, t, u

Notice that we assigned string s to u. Intuitively we would expect that u holds the value "Bath" that was, in effect, assigned to it, and we do not expect that applying += to s will have any side effects, even though both s and u refer to the same string. And our intuition is correct: u's value is not changed because when += is applied to s,a new string object is created and bound to s, and u is left as the only object now referring to the original "Bath" string.

Was this article helpful?

0 0
Tube Jacker

Tube Jacker

Download Tube Jacker And Discover Everything You Need To Know About Jacking Unlimited Traffic From The Video Giant. The drop dead easy way to create winning video campaigns that will FLOOD your website with unstoppable FREE traffic, all on complete and total autopilot. How to exploit a sneaky method of boosting exposure and getting your videos to the top of Google within 72 hours, guaranteed.

Get My Free Ebook


Post a comment