Dictionaries as records

Steve Holden sholden at holdenweb.com
Wed Dec 19 10:44:58 EST 2001


"Bill Wilkinson" <bwilk_97 at yahoo.com> wrote in message
news:F82U7.28866$t07.4111647 at twister.midsouth.rr.com...
>
> "John Roth"
> > In this case, you have one copy of each of your input
> > strings, not 15000 copies! The memory usage should be
> > pretty close to pure dictionary overhead.
>
> I don't see how that can be. If they were all copies of the same
reference,
> wouldn't a change in one record be reflected in all?  Below I make a
change
> to one record and the others remain the same:
>
> >>>tbl[1]["g11"]  #original value
>  'ldjfljdfkjdf'
> >>> tbl[1]["g11"] = "f"  #change rec one to 'f'/
> >>> tbl[1]["g11"]    #it's value is different now.
> 'f'
> >>> tbl[2]["g11"]    #rec 2 remains the same.
> 'ldjfljdfkjdf'
>
>
> Now the question. Am I misunderstanding what is happening above?
>
Indeed you are. Observe:

>>> a = "1234"
>>> b = a
>>> a = "1235"
>>> b
'1234'

Here the name a is rebound to a new value, and the name b remains bound to
its original value. But:

>>> a = ["a", "b", "c"]
>>> b = a
>>> a[1] = "SECOND"
>>> b
['a', 'SECOND', 'c']
>>>

Here the name a is bound to a MUTABLE value, as is b. The assignment to a[1]
changes the mutable value which both names are bound to. Finally ...

>>> a = "banana"
>>> b
['a', 'SECOND', 'c']
>>>

Here again a is rebound rather than remaining bound to the same value. Again
b remains bound to the origial value.

Does this make it any clearer? Variables don't hold values, they hold
*references* to values. That's why pythonistas frequently refer to name
binding rather than assignment.

Hope this helps.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list