Why does str(aList) use repr() on the list's elements?

Peter Hansen peter at engcorp.com
Sun Aug 18 03:17:50 EDT 2002

Jeremy Fincher wrote:
> The subject pretty much says it all -- one would think that the str()
> of a list would use str() on its elements, but it uses repr() instead.
>  Why is this?

The documentation says str() should return "a nice string representation
of the object".  What would happen if you did str() on the elements of
a list where the elements contained binary information?  You'd get a 
real mess when you tried to print the list.  The list is the collection,
not the elements themselves, so you want the "nice representation" to
look like a clean list, not something that depends on the exact contents.

For example, how about this:
>>> s = ['[', ']]', ]
>>> jeremyListStr(s)
[ [, ]] ]
>>> s
['[', ']]']

It's easier to tell what the items in the list are in the second case.
(Yes, very contrived example, but there are probably other such cases.)


More information about the Python-list mailing list