Search code examples
pythonpython-3.xiterablegenerator-expression

Turn iterable of tuple into iterables of each element (Python)


I have an iterable delta that generates tuple of two numbers (dx, dy), and I want to compute the sum of each. The following doesn't work since delta is disposed after the first iteration.

x = sum(dx for dx, dy in delta)
y = sum(dy for dx, dy in delta)

Any idea? I'm thinking in the direction of somehow turning delta into two iterables of dx and dy, but have reached nothing so far.


Solution

  • Use zip() and map() functions to apply the sum() on each column:

    x, y = map(sum, zip(*delta))