Creating a List of Empty Lists

David M. Cooke cookedm+news at physics.mcmaster.ca
Fri Dec 5 22:50:36 CET 2003


At some point, "r.e.s." <r.s at XXmindspring.com> wrote:

> But something's wrong with that explanation, because 
> of the following:
>
>     >>> a = 'gobble'
>     >>> a is 'gobble'
>     True
>
> Surely `'gobble'` is not the name of an already-existing 
> object, so I expected exactly the same result as for 
> `100` and `[]`.  What's going on there?  

Actually, your second use of 'gobble' *is* an already-existing object.
Python 'interns' string constants, i.e., reuses them. Check this out
>>> a = 'gobble'
>>> a is 'gobble'
True
>>> a is ('gob' + 'ble')
False
>>> a = 'gob' + 'ble'
>>> a is 'gobble'
False

Here, the constants 'gobble', 'gob', and 'ble' are interned. Computed
strings are not looked up and replaced, so 'gob' + 'ble' is not
'gobble'.

Compare with (in a new interpreter!)

>>> a = 'gob' + 'ble'
>>> intern(a)
'gobble'
>>> a is 'gobble'
True

Here, we've explicitly interned the result of 'gob' + 'ble', so it is
the same as 'gobble'.

But, don't depend on interning. Use == to compare strings.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca




More information about the Python-list mailing list