Creating a List of Empty Lists

Robin Munn rmunn at pobox.com
Sat Dec 6 12:06:07 EST 2003


r.e.s. <r.s at XXmindspring.com> wrote:
> "David M. Cooke" wrote ...
>> "r.e.s." 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. 
><snip>
>
> Thanks. That explains it.

But take note that this behavior is not guaranteed anywhere in the language
reference. As someone else said in this thread, don't count on interning.
Sometimes it will happen, and sometimes it won't:

>>> a = 'gobble'
>>> a is gobble
True
>>> b = 'foo bar'
>>> b is 'foo bar'
False

The rule of thumb is that Python interns a string if it's likely to be used
as a name (i.e., only alphanumerics and underscores). The string 'foo bar'
has a space and would be an invalid name, so it wasn't interned.

-- 
Robin Munn
rmunn at pobox.com




More information about the Python-list mailing list