What is the preferred way to concatenate sequences in Python 3?
what is wrong with:
from itertools import chain
def chain_sequences(*sequences):
return chain(*sequences)
I'd use itertools.chain.from_iterable()
instead:
import itertools
def chained(sequences):
return itertools.chain.from_iterable(sequences):
or, since you tagged this with python-3.3 you could use the new yield from
syntax (look ma, no imports!):
def chained(sequences):
for seq in sequences:
yield from seq
which both return iterators (use list()
on them if you must materialize the full list). Most of the time you do not need to construct a whole new sequence from concatenated sequences, really, you just want to loop over them to process and/or search for something instead.
Note that for strings, you should use str.join()
instead of any of the techniques described either in my answer or your question:
concatenated = ''.join(sequence_of_strings)
Combined, to handle sequences fast and correct, I'd use:
def chained(sequences):
for seq in sequences:
yield from seq
def concatenate(sequences):
sequences = iter(sequences)
first = next(sequences)
if hasattr(first, 'join'):
return first + ''.join(sequences)
return first + type(first)(chained(sequences))
This works for tuples, lists and strings:
>>> concatenate(['abcd', 'efgh', 'ijkl'])
'abcdefghijkl'
>>> concatenate([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> concatenate([(1, 2, 3), (4, 5, 6), (7, 8, 9)])
(1, 2, 3, 4, 5, 6, 7, 8, 9)
and uses the faster ''.join()
for a sequence of strings.
Use itertools.chain.from_iterable
.
import itertools
def concatenate(sequences):
return list(itertools.chain.from_iterable(sequences))
The call to list
is needed only if you need an actual new list, so skip it if you just iterate over this new sequence once.