Python: why str.join() and not list.join()

or “Slowpoke finally understands Python

When I was in Australia, one guy kept asking why Python had the “horrible” (in his opinion) str.join() instead of obvious (in his opinion) list.join()?

After working with JavaScript for a while, I can understand his opinion: In JS, you have a list.join() of sorts and it makes a hell lot of sense.

But, then again, this morning it finally hit me: str.join() uses an iterable object as parameter, so any iterable object will work. For example:

>>> p = 'python'
>>> '-'.join(p)
'p-y-t-h-o-n'
>>>

Ok, this is understandable, but why not have a list.join() too? Well, this would mean that every iterable object would have to have a join() method (str.join(), tuple.join(), dict.join(), list.join() and all the new iterable objects that appeared in Python 3.0.) Since the C API for Python doesn’t allow object hierarchies (and all base types are implemented in C), the same method would have to be implemented over and over again. Not only that, but you would have several different ways to join() stuff instead of one, (now) obvious way.

Another way to fix this would monkey-patch every object to have a join() method, but that’s not the Python way. Monkey-patch is never the Python way.

And the same rule applies to len(): it takes any iterable due the same reason.