How to do * and & C-lang. operations in Python?

Chris Barker chrishbarker at home.net
Thu Sep 20 16:48:35 EDT 2001


Gerhard Häring wrote:

> > I have a variable defined on one module, and want to use _exactly_ the
> > same variable in other module. Example:

> > Assignaments are done by 'value', not by 'reference'. Function calls
> > are done by 'reference'. How to do assignaments by reference?

no, not exactly. Here is an example:
>>> a = 5 # a is a refernce to the integer object: 5
>>> b = a # b is a reference to the same object as a
>>> a is b 
1
# they are the same object
>>> a
5
>>> b
5
# they have the same value
>>> a = 3 # is now a reference to a different integer object: 3
>>> a
3
>>> b
5
>>> a is b
0
# a and b now point to different objects

Assignment is a reference, but integers are an immutable type, so they
can't be changed. When you re-assign a variable, you have to point it to
a new object. Other immutable objects are tuples, stings, other numbers.

If, on the other hand you use a mutable object, it can be changed in
place. lists, dictionaries, classes, etc are mutable types, so you can
do what was suggested:

> Use instances of classes. Assignments work by reference with class
> instances.

but you can also use any mutable type:
>>> a = [1,2,3]
>>> b = a
>>> a is b
1
>>> a[0] = 10
>>> a
[10, 2, 3]
>>> b
[10, 2, 3]
>>> b[2] = 30
>>> a
[10, 2, 30]
>>> b
[10, 2, 30]

In this case, a and b both refer to the same list, so when the list is
changed, they are both affected. NOte that if you want a copy of a list
instead, you can do:

>>> a = [1,2,3]
>>> b = a[:]
>>> a is b
0

slicing returns a reference to a copy, not a refernce to the list
itself.

In python it is easier to think in terms of mutable vs. immutable types,
rather than references vs. copies.

-Chris


-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list