Creating a List of Empty Lists

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

At some point, "r.e.s." <r.s at> 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'
>>> a is ('gob' + 'ble')
>>> a = 'gob' + 'ble'
>>> a is 'gobble'

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

Compare with (in a new interpreter!)

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

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

More information about the Python-list mailing list