why () is () and [] is [] work in other way?

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Fri Apr 20 15:37:47 EDT 2012


dmitrey <dmitrey15 at gmail.com> writes:

> I have spent some time searching for a bug in my code, it was due to
> different work of "is" with () and []:
>>>> () is ()
> True
>>>> [] is []
> False
>
> (Python 2.7.2+ (default, Oct  4 2011, 20:03:08)
> [GCC 4.6.1] )
>
> Is this what it should be or maybe yielding unified result is better?

Tuples are immutable, while lists are not. Because tuples are immutable,
there is no point in having several empty tuples: one value is enough,
and "is" recognizes this. Lists are different, they can change "value"
(contents), and several names can be bound to the same list (in other
words, you can have side-effects on a list). With:

   a = []
   b = a
   a.append(42)
   print b

you get [42]. If instead you do:

   a = []
   b = []
   a.append(42)
   print b

you get the expected []. I.e., you need several distinct empty lists,
to make sure they can change value independently.

(In case you wonder: lists in Python are not linked lists of cons-cells,
they are more monolithic structures, and two lists cannot share a common
tail.)

-- Alain.



More information about the Python-list mailing list