How can I concatenate different tuples inside a list to a single tuple inside a list in Python?
Current form:
[('1st',), ('2nd',), ('3rd',), ('4th',)]
Desired form:
[('1st', '2nd', '3rd', '4th')]
How can I concatenate different tuples inside a list to a single tuple inside a list in Python?
Current form:
[('1st',), ('2nd',), ('3rd',), ('4th',)]
Desired form:
[('1st', '2nd', '3rd', '4th')]
What you're trying to do is "flatten" a list of tuples. The easiest and most pythonic way is to simply use (nested) comprehension:
tups = [('1st',), ('2nd',), ('3rd',), ('4th',)]
tuple(item for tup in tups for item in tup)
result:
('1st', '2nd', '3rd', '4th')
You can wrap the resulting tuple in a list if you really want.
EDIT:
I also like Alan Cristhian's answer, which is basically transposing a column vector into a row vector:
list(zip(*tups))
Seems like this will do it:
import itertools
tuples = [('1st',), ('2nd',), ('3rd',), ('4th',)]
[tuple(itertools.chain.from_iterable(tuples))]
>>> l = [('1st',), ('2nd',), ('3rd',), ('4th',)]
>>> list(zip(*l))
[('1st', '2nd', '3rd', '4th')]
See also: Using the Python zip() Function for Parallel Iteration
Simple solution:
tups = [('1st',), ('2nd',), ('3rd',), ('4th',)]
result = ()
for t in tups:
result += t
# [('1st', '2nd', '3rd', '4th')]
print([result])
Here's another one - just for fun:
[tuple([' '.join(tup) for tup in tups])]