I have two iterable objects and want to chain them, i.e. concatenate them. Specifically, being iterable the objects return an iterator, and this can be repeated. The concatenation of these two iterables should be an iterable that gets the two iterators from the inputs each time and returns the concetenated iterator. I am still fairly new to Python and find it very subtle and quite difficult - not like the "easy" language everyone tells me it is. But I would have thought there'd be a simple way to do this particular task. Note chain from itertools doesn't work:
from itertools import chain
def i():
n = 0
while n < 2:
yield n
n = n+1
def j():
m = 0
while m < 3:
yield m
m = m+1
print("iterating i")
for x in i():
print(x)
print("iterating i again")
for x in i():
print(x)
k = chain(i(),j())
print("iterating k")
for x in k:
print(x)
print("iterating k again")
for y in k:
print(y)
print("but it's empty :(")
giving
iterating i
0
1
iterating i again
0
1
iterating k
0
1
0
1
2
iterating k again
but it's empty :(
Here chain seems to operate on the iterators giving an iterator, but I want to chain two iterables giving an iterable.
Responses to initial comments:
I don't think this is a question about generators: I just used generators to illustrate.
Some people have said the iterable has run out of stuff. But as I understand it, that is not right: the iterable can always make new iterators. You can see that i() can be repeated. One particular iterator has been exhausted. This question is about the difference between iterator and iterable.
Finally, of course I could save the data in a list and iterate as many times as I like over that list. But I want you to imagine that 2 and 3 are so huge that this is impractical.
Thanks in advance :)