What is the preferred way to concatenate sequences in Python 3?
Right now, I'm doing:
import functools
import operator
def concatenate(sequences):
return functools.reduce(operator.add, sequences)
print(concatenate([['spam', 'eggs'], ['ham']]))
# ['spam', 'eggs', 'ham']
Needing to import two separate modules to do this seems clunky.
An alternative could be:
def concatenate(sequences):
concatenated_sequence = []
for sequence in sequences:
concatenated_sequence += sequence
return concatenated_sequence
However, this is incorrect because you don't know that the sequences are lists.
You could do:
import copy
def concatenate(sequences):
head, *tail = sequences
concatenated_sequence = copy.copy(head)
for sequence in sequences:
concatenated_sequence += sequence
return concatenated_sequence
But that seems horribly bug prone -- a direct call to copy? (I know head.copy()
works for lists and tuples, but copy
isn't part of the sequence ABC, so you can't rely on it... what if you get handed strings?). You have to copy to prevent mutation in case you get handed a MutableSequence
. Moreover, this solution forces you to unpack the entire set of sequences first. Trying again:
import copy
def concatenate(sequences):
iterable = iter(sequences)
head = next(iterable)
concatenated_sequence = copy.copy(head)
for sequence in iterable:
concatenated_sequence += sequence
return concatenated_sequence
But come on... this is python! So... what is the preferred way to do this?