New submission from Javier Dehesa <[email protected]>:
It is pretty trivial to concatenate a sequence of strings:
''.join([str1, str2, ...])
Concatenating a sequence of lists is for some reason significantly more
convoluted. Some current options include:
sum([lst1, lst2, ...], [])
[x for y [lst1, lst2, ...] for x in y]
list(itertools.chain(lst1, lst2, ...))
The first one being the less recomendable but more intuitive and the third one
being the faster but most cumbersome (see
https://stackoverflow.com/questions/49631326/why-is-itertools-chain-faster-than-a-flattening-list-comprehension
). None of these looks like "the one obvious way to do it" to me. Furthermore,
I feel a dedicated concatenation method could be more efficient than any of
these approaches.
If we accept that ''.join(...) is an intuitive idiom, why not provide the
syntax:
[].join([lst1, lst2, ...])
And while we are at it:
().join([tpl1, tpl2, ...])
Like with str, these methods should only accept sequences of objects of their
own class (e.g. we could do [].join(list(s) for s in seqs) if seqs contains
lists, tuples and generators). The use case for non-empty joiners would
probably be less frequent than for strings, but it also solves a problem that
has no clean solution with the current tools. Here is what I would probably do
to join a sequence of lists with [None, 'STOP', None]:
lsts = [lst1, lst2, ...]
joiner = [None, 'STOP', None]
lsts_joined = list(itertools.chain.from_iterable(lst + joiner for lst in
lsts))[:-len(joiner)]
Which is awful and inefficient (I am not saying this is the best or only
possible way to solve it, it is just what I, self-considered experienced Python
developer, might write).
----------
components: Library (Lib)
messages: 314881
nosy: Javier Dehesa
priority: normal
severity: normal
status: open
title: join method for list and tuple
type: enhancement
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue33214>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com