Section 3.2. Variable Assignment


3.2. Variable Assignment

This section focuses on variable assignment. We will discuss which identifiers make valid variables in Section 3.3.

Assignment Operator

The equal sign ( = ) is the main Python assignment operator. (The others are augmented assignment operator [see next section].)

  anInt = -12   aString = 'cart'   aFloat = -3.1415 * (5.0 ** 2)   anotherString = 'shop' + 'ping'   aList = [3.14e10, '2nd elmt of a list', 8.82-4.371j]


Be aware now that assignment does not explicitly assign a value to a variable, although it may appear that way from your experience with other programming languages. In Python, objects are referenced, so on assignment, a reference (not a value) to an object is what is being assigned, whether the object was just created or was a pre-existing object. If this is not 100 percent clear now, do not worry about it. We will revisit this topic later on in the chapter, but just keep it in mind for now.

Also, if you are familiar with C, you know that assignments are treated as expressions. This is not the case in Python, where assignments do not have inherent values. Statements such as the following are invalid in Python:

  >>> x = 1   >>> y = (x = x + 1)  # assignments not expressions!     File "<stdin>", line 1       y = (x = x + 1)              ^   SyntaxError: invalid syntax


Chaining together assignments is okay, though (more on this later):

  >>> y = x = x + 1   >>> x, y   (2, 2)


Augmented Assignment

Beginning in Python 2.0, the equal sign can be combined with an arithmetic operation and the resulting value reassigned to the existing variable. Known as augmented assignment, statements such as ...

   x = x + 1


... can now be written as ...

   x += 1


Augmented assignment refers to the use of operators, which imply both an arithmetic operation as well as an assignment. You will recognize the following symbols if you come from a C/C++ or Java background:

     +=          -=        *=    /=     %=        **=      <<=   >>=         &=    ^= |=


Other than the obvious syntactical change, the most significant difference is that the first object (A in our example) is examined only once. Mutable objects will be modified in place, whereas immutable objects will have the same effect as A = A + B (with a new object allocated) except that A is only evaluated once, as we have mentioned before.

   >>> m = 12    >>> m %= 7    >>> m    5    >>> m **= 2    >>> m    25    >>> aList = [123, 'xyz']    >>> aList += [45.6e7]    >>> aList    [123, 'xyz', 456000000.0]


Python does not support pre-/post-increment nor pre-/post-decrement operators such as x++ or --x.

Multiple Assignment

  >>> x = y = z = 1   >>> x   1   >>> y   1   >>> z   1


In the above example, an integer object (with the value 1) is created, and x, y, and z are all assigned the same reference to that object. This is the process of assigning a single object to multiple variables. It is also possible in Python to assign multiple objects to multiple variables.

"Multuple" Assignment

Another way of assigning multiple variables is using what we shall call the "multuple" assignment. This is not an official Python term, but we use "multuple" here because when assigning variables this way, the objects on both sides of the equal sign are tuples, a Python standard type we introduced in Section 2.8.

  >>> x, y, z = 1, 2, 'a string'   >>> x   1   >>> y   2   >>> z   'a string'


In the above example, two integer objects (with values 1 and 2) and one string object are assigned to x, y, and z respectively. Parentheses are normally used to denote tuples, and although they are optional, we recommend them anywhere they make the code easier to read:

   >>> (x, y, z) = (1, 2, 'a string')


If you have ever needed to swap values in other languages like C, you will be reminded that a temporary variable, i.e., tmp, is required to hold one value while the other is being exchanged:

  /* swapping variables in C */   tmp = x;   x = y;   y = tmp;


In the above C code fragment, the values of the variables x and y are being exchanged. The tmp variable is needed to hold the value of one of the variables while the other is being copied into it. After that step, the original value kept in the temporary variable can be assigned to the second variable.

One interesting side effect of Python's "multuple" assignment is that we no longer need a temporary variable to swap the values of two variables.

  # swapping variables in Python   >>> x, y = 1, 2   >>> x   1   >>> y   2   >>> x, y = y, x   >>> x   2   >>> y   1


Obviously, Python performs evaluation before making assignments.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net