BartDur - 5 months ago 20

Python Question

I am using python built-in function zip() to combine two lists:

`l1 = [1,2,3]`

l2 = [4,5,6]

zipped = zip(l1,l2)

Is it possible to 'add' to this zipped object, for example:

`l3 = [7,8,9]`

zipped2 = zipped.add(l3)

Such that:

`list(zipped2)`

Would yield:

`[(1,4,7),(2,5,8),(3,6,9)]`

I tried for example:

`zipped2 = zip(zipped,l3)`

But this results in:

`[((1, 4), 7), ((2, 5), 8), ((3, 6), 9)]`

(which makes sense)

An obvious approach would be to 'unzip' zipped and then zip() again including the new list, however, this is not practical for my application is I would like to add a variable amount of lists depending on some logic, so I am wondering if there already is some built in function that does this. I checked itertools and did not find an obvious candidate.

If one could point me in the right direction that would be highly appreciated.

Answer

One way would be to write your own generator:

```
def add_to_zip(zipped, lst):
for tpl, elem in zip(zipped, lst):
yield tpl + (elem,)
zipped2 = add_to_zip(zipped, l3)
list(zipped2)
# OUT: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
```

If you want to extend it to an arbitrary number of lists:

```
def add_to_zip2(zipped, *lists):
for tpl, *elems in zip(zipped, *lists):
yield tpl + tuple(elems)
zipped3 = add_to_zip2(zipped, l3, l2)
list(zipped3)
# OUT: [(1, 4, 7, 4), (2, 5, 8, 5), (3, 6, 9, 6)]
```