I l@ve RuBoard Previous Section Next Section

3.1 Assignment

We've been using the Python assignment statement already, to assign objects to names. In its basic form, you write a target of an assignment on the left of an equals sign and an object to be assigned on the right. The target on the left may be a name or object component, and the object on the right can be an arbitrary expression that computes an object. For the most part, assignment is straightforward to use, but here are a few properties to keep in mind:

Assignments create object references

As we've already seen, Python assignment stores references to objects in names or data structure slots. It always creates references to objects, instead of copying objects. Because of that, Python variables are much more like pointers than data storage areas as in C.

Names are created when first assigned

As we've also seen, Python creates variable names the first time you assign them a value (an object reference). There's no need to predeclare names ahead of time. Some (but not all) data structure slots are created when assigned too (e.g., dictionary entries, some object attributes). Once assigned, a name is replaced by the value it references when it appears in an expression.

Names must be assigned before being referenced

Conversely, it's an error to use a name you haven't assigned a value to yet. Python raises an exception if you try, rather than returning some sort of ambiguous (and hard to notice) default value.

Implicit assignments: import, from, def, class, for, function arguments, etc.

In this section, we're concerned with the = statement, but assignment occurs in many contexts in Python. For instance, we'll see later that module imports, function and class definitions, for loop variables, and function arguments are all implicit assignments. Since assignment works the same everywhere it pops up, all these contexts simply bind names to object references at runtime.

Table 3.2 illustrates the different flavors of the assignment statement in Python.

Table?.2. Assignment Statement Forms

Operation

Interpretation

spam = 'Spam'

Basic form

spam, ham = 'yum', 'YUM'

Tuple assignment (positional)

[spam, ham] = ['yum', 'YUM']

List assignment (positional)

spam = ham = 'lunch'

Multiple-target

The first line is by far the most common: binding a single object to a name (or data-structure slot). The other table entries represent special forms:

Tuple and list unpacking assignments

The second and third lines are related. When you use tuples or lists on the left side of the =, Python pairs objects on the right side with targets on the left and assigns them from left to right. For example, in the second line of the table, name spam is assigned the string 'yum', and name ham is bound to string 'YUM'. Internally, Python makes a tuple of the items on the right first, so this is often called tuple (and list) unpacking assignment.

Multiple-target assignments

The last line shows the multiple-target form of assignment. In this form, Python assigns a reference to the same object (the object farthest to the right) to all the targets on the left. In the table, names spam and ham would both be assigned a reference to the string 'lunch', and so share the same object. The effect is the same as if you had coded ham='lunch', followed by spam=ham, since ham evaluates to the original string object.

Here's a simple example of unpacking assignment in action. We introduced the effect of the last line in a solution to the exercise from Chapter 2: since Python creates a temporary tuple that saves the items on the right, unpacking assignments are also a way to swap two variables' values without creating a temporary of our own.

>>> nudge = 1
>>> wink  = 2
>>> A, B = nudge, wink             # tuples
>>> A, B
(1, 2)
>>> [C, D] = [nudge, wink]         # lists
>>> C, D
(1, 2)
>>> nudge, wink = wink, nudge      # tuples: swaps values
>>> nudge, wink                    # same as T=nudge; nudge=wink; wink=T
(2, 1)

3.1.1 Variable Name Rules

Now that we've told you the whole story of assignment statements, we should also get a bit more formal in our use of variable names. In Python, names come into existence when you assign values to them, but there are a few rules to follow when picking names for things in our program. Python's variable name rules are similar to C's:

Syntax: (underscore or letter) + (any number of letters, digits, or underscores)

Variable names must start with an underscore or letter, and be followed by any number of letters, digits, or underscores. _spam, spam, and Spam_1 are legal names, but 1_Spam, spam$, and @#! are not.

Case matters: SPAM is not the same as spam

Python always pays attention to case in programs, both in names you create and in reserved words. For instance, names X and x refer to two different variables.

Reserved words are off limits

Names we define cannot be the same as words that mean special things in the Python language. For instance, if we try to use a variable name like class, Python will raise a syntax error, but klass and Class work fine. The list below displays the reserved words (and hence off limits to us) in Python.

and

assert

break

class

continue

def

del

elif

else

except

exec

finally

for

from

global

if

import

in

is

lambda

not

or

pass

print

raise

return

try

while

?/FoNT> ?/foNT>

Before moving on, we'd like to remind you that it's crucial to keep Python's distinction between names and objects clear. As we saw in Chapter 2, objects have a type (e.g., integer, list), and may be mutable or not. Names, on the other hand, are just references to objects. They have no notion of mutability and have no associated type information apart from the type of the object they happen to be bound to at a given point in time. In fact, it's perfectly okay to assign the same name to different kinds of objects at different times:

>>> x = 0            # x bound to an integer object
>>> x = "Hello"      # now it's a string
>>> x = [1, 2, 3]    # and now it's a list

In later examples, we'll see that this generic nature of names can be a decided advantage in Python programming.[1]

[1] If you've used C++ in the past, you may be interested to know that there is no notion of C++'s const declaration in Python; certain objects may be immutable, but names can always be assigned. Or usually; as we'll see in later chapters, Python also has ways to hide names in classes and modules, but they're not the same as C++'s declarations.

I l@ve RuBoard Previous Section Next Section