[Python-ideas] Add list.join() please

Chris Angelico rosuav at gmail.com
Tue Jan 29 01:04:23 EST 2019

On Tue, Jan 29, 2019 at 4:48 PM David Mertz <mertz at gnosis.cx> wrote:
> In the first case, the object (a heterogenous list) can NEVER support a .join() method. It's simply the wrong kind of object. Of course, it's right as far as the basic type system goes, but its deeper (maybe "structural") type cannot support that method.
> On the other hand, sure, almost any function, including methods, will choke on bad arguments. But no string *object* rules out joining if good arguments can be found.
> I am sure readers will immediately reply, "what about list.sort()?" Unfortunately, that really will simply fail on lists of the wrong "type." After all these years, I still think that change in Python 2.3 or so was the wrong choice (for those with fewer gray hairs: when the hills were young, Python objects were arbitrarily comparable under inequality, even when the answer didn't "mean" anything).

Considering that you can provide a key function to sort(), there is by
definition no list of objects which utterly cannot be sorted.

That said, though, I don't think this is an overly strong argument.
The main reason lists don't have a join method is that str.join() can
take *any iterable*, so it's perfectly legal to join tuples or
generators without needing to listify them. Consider:

# Join the parts, ignoring empty ones
"_".join(filter(None, parts))

c = collections.Counter(...)
"_".join(item for item, count in c.most_common())

# solving Brendan's complaint of perversity
"_".join(map(str, stuff))

If these were flipped around, you'd have to explicitly call list() on
them just to get a join method.

BTW, Ronie: I would disagree. Python uses syntactic elements only
where functions are incapable of providing equivalent functionality.
That's why print became a function in 3.0 - it didn't need to be
magical syntax any more.


More information about the Python-ideas mailing list