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

Brendan Barnwell brenbarn at brenbarn.net
Tue Jan 29 00:05:00 EST 2019


On 2019-01-28 18:22, David Mertz wrote:
> On Mon, Jan 28, 2019 at 8:44 PM Jamesie Pic <jpic at yourlabs.org
> <mailto:jpic at yourlabs.org>> wrote:
>
>     ['cancel', name].join('_')
>
>
> This is a frequent suggestion.  It is also one that makes no sense
> whatsoever if you think about Python's semantics.  What would you expect
> to happen with this line:
>
> ['foo', b'foo', 37, re.compile('foo')].join('_')
>
>   List are not restricted to containing only strings (or things that are
> string-like enough that they might play well with joining).  Growing a
> method that pertains only to that specialized sort of list breaks the
> mental model of Python.  Moreover, there is no way to TELL if a
> particular list is a "list of strings" other than checking each item
> inside it (unlike in many languages).

	That problem already exists with str.join though.  It's just currently 
spelled this way:

','.join(['foo', b'foo', 37, re.compile('foo')])

	. . . and the result is an error.  I don't see how it's semantically 
any less sensible to call list.join on a list of non-string things than 
it is to pass a list of non-string things to str.join.

	Personally what I find is perverse is that .join is a method of strings 
but does NOT call str() on the items to be joined.  The cases where I 
would have been surprised or bitten by something accidentally being 
converted to a string are massively outweighed by the cases where I want 
everything to be converted into a string, because, dangit, I'm joining 
them into a bigger string.

	I agree that a list method would be nice, but we then have to think 
about should we add similar methods to all iterable types, since 
str.join can take any iterable (not just a list).

-- 
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is no 
path, and leave a trail."
    --author unknown


More information about the Python-ideas mailing list