How can you add tuples together in an internal loop?

Question:

I would like to add all elements in list1 in one big tuple with a concise expression.
The output of list2 gives the representation I would like to have,
how am I able to achieve this with list3?
The expression for list2 isn’t convenient if I have a lot of internal tuples.

list1 = ((1,2,3),(4,5,6),(7,8,9),(10,11,12))

list2 = tuple(list1[0] + list1[1] + list1[2] + list1[3])

print(list2)

list3 = tuple(list1[i] for i in range(4))

print(list3)

OUTPUT list2: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

OUTPUT list3: ((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12))

I figured out that list2 uses addition to add the tuples but the for loop in list3 uses comma’s.
Is there a way to indicate that the internal for loop has to add the tuples via addition?

Asked By: F21

||

Answers:

The inline for loop will always create as many elements as you put after the in.

For a quick way to get the result you are looking for, you can use the reduce function to add the tuples together.

>>> import functools
>>> import operator
>>> functools.reduce(operator.concat, list1)
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

operator.concat in this case is just a function specifying how to handle the objects. It can be rewritten with functools.reduce((lambda x,y: x+y), list1)

EDIT: For your simple problem the above solution will work. However as pointed out by @ShadowRanger this will not be very efficient with much larger inputs.

Here is an example of how you could use itertools.chain.from_iterable in your case:

>>> import itertools
>>> tuple(itertools.chain.from_iterable(list1))
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
Answered By: Tim Woocker
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.