Qi Chen
Qi Chen

Reputation: 1718

Append tuple elements to a tuple of tuples in Python

If I have a tuple, e.g. x = (1, 2, 3) and I want to append each of its elements to the front of each tuple of a tuple of tuples, e.g. y = (('a', 'b'), ('c', 'd'), ('e', 'f')) so that the final result is z = ((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f')), what is the easiest way?

My first thought was zip(x,y), but that produces ((1, ('a', 'b')), (2, ('c', 'd')), (3, ('e', 'f'))).

Upvotes: 2

Views: 560

Answers (2)

timgeb
timgeb

Reputation: 78790

Use zip and flatten the result:

>>> x = (1, 2, 3)
>>> y = (('a', 'b'), ('c', 'd'), ('e', 'f'))
>>> tuple((a, b, c) for a, (b, c) in zip(x,y))
((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f'))

Or, if you are using Python 3.5, do it in style:

>>> tuple((head, *tail) for head, tail in zip(x,y))
((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f'))

Upvotes: 3

Eli Korvigo
Eli Korvigo

Reputation: 10513

tuple((num, ) + other for num, other in zip(x, y))

Or

from itertools import chain

tuple(tuple(chain([num], other)) for num, other in zip(x, y))

Upvotes: 2

Related Questions