str() for containers

Dan Bishop danb_83 at
Fri Jun 18 07:53:44 CEST 2004

Donn Cave <donn at> wrote in message news:<donn-65345D.10415616062004 at>...
> In article <40d07ac6 at>,
>  "George Sakkis" <gsakkis at> wrote:
> > I find the string representation behaviour of builtin containers
> > (tuples,lists,dicts) unintuitive in that they don't call recursively str()
> > on their contents (e.g. as in Java)
> Please find last week's answers to this question at
> If you're still interested in further discussion of this
> point, you could present an account of Java's approach
> for the edification of those of us who don't know.

All Java classes include a toString() method (defined in the root
class java.lang.Object), which returns the string representation of
that object.  Each of the standard collection classes in java.util
defines its toString() method to recursively call toString() on its

For example, the program

   import java.util.*;
   public class Foo {
      public static void main(String[] args) {
         List lst = new ArrayList();

prints "[a, b, c]".

(Btw, this reminds me of something I like about Python: There are
literals for variable length arrays, so you don't have to write code
like that.)

The difference from Python's approach is that there isn't an
equivalent to Python's str/repr distinction.  Obviously, when there's
only one string conversion method, you won't use the wrong one.

The other difference is that the built-in array types don't have a
meaningful toString() method, so

   public class Foo {
      public static void main(String[] args) {
         String[] arr = {"a", "b", "c"};

prints "[Ljava.lang.String;@df6ccd" (or something similar).

More information about the Python-list mailing list