0

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?

F21
  • 21
  • 3

1 Answers1

2

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)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Tim Woocker
  • 1,883
  • 1
  • 16
  • 29
  • Note: This is the wrong way to do it for (potentially) large inputs; it's a [Schlemiel the Painter's algorithm](https://en.wikipedia.org/wiki/Schlemiel_the_Painter's_algorithm). `itertools.chain.from_iterable` avoids that problem, with no additional code complexity. – ShadowRanger Apr 12 '21 at 11:04
  • This is an unnecessarily inefficient algorithm. It should be avoided since it is trivial to not have the quadratic behavior. – juanpa.arrivillaga Apr 12 '21 at 11:24
  • Thank you @ShadowRanger - I edited the answer with a corresponding example – Tim Woocker Apr 12 '21 at 11:31
  • @juanpa.arrivillaga Thank you for your comment. I edited my answer with an example for a more efficient approach. – Tim Woocker Apr 12 '21 at 11:34