2

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'))).

2 Answers 2

3

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'))
Sign up to request clarification or add additional context in comments.

Comments

2
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))

2 Comments

I don't see any benefit to the chain version.
@AlexHall it's just another option for the record.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.