Holzhacker
Holzhacker

Reputation: 59

Is it possible to sum iterators?

For example, I have the following code:

def functionx(n):
    i = 0
    while i < 3:
        n += 2
        yield n
        i += 1



for i in functionx(x):
    op2 = i

for m in functionx(y):
    op1 = m

And then sum op2 and op1, for example, but with the first yield, then do same for the second until i hits 3

Upvotes: 3

Views: 125

Answers (2)

thefourtheye
thefourtheye

Reputation: 239503

You can use itertools.izip. It does what exactly you are looking for. It iterates over both the iterators simultaneously, but lazily.

from itertools import izip

for i, m in izip(functionx(x), functionx(y)):
     print i + m

The difference between zip and itertools.izip in Python 2.x is

def functionx(n):
    i = 0
    while i < 3:
        n += 2
        print n
        yield n
        i += 1

Using zip,

for i, m in zip(functionx(3), functionx(3)):
    print "Sum", i + m

Output

5
5
7
7
9
9
Sum 10
Sum 14
Sum 18

Using itertools.izip,

from itertools import izip for i, m in izip(functionx(3), functionx(3)): print "Sum", i + m

Output

5
5
Sum 10
7
7
Sum 14
9
9
Sum 18

As you can see, itertools.izip iterates only on demand.

Note: In Python 3.x, there is no izip, the default behavior of zip itself is similar to that of izip.

Upvotes: 2

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

for i,m in zip(functionx(x), functionx(y)):
    result = i + m

Edit: Aaron Hall makes a good point - if one generated sequence is longer than the other, you might want to

# from itertools import izip_longest as zl    # Python 2.x
from itertools import zip_longest as zl     # Python 3.x

for i,m in zl(functionx(x), functionx(y), fillvalue=0):
    result = i + m

Upvotes: 2

Related Questions