Reputation: 1195
Give lists a, b
a = [5, 8, 9]
b = [6, 1, 0]
I want to create a generator gen such that:
for x in gen:
print x
outputs
5, 8, 9, 6, 1, 0
Upvotes: 6
Views: 4653
Reputation: 1935
You could use generator expressions for a ridiculously pythonic and elegant one-liner:
>>> a=[5,8,9]
>>> b=[6,1,0]
>>> g=(i for i in a+b)
test:
>>> for i in g:
print i
5
8
9
6
1
0
or test #2, if you really prefer to have a comma between each item, :
>>> print ', '.join(map(str,g))
5, 8, 9, 6, 1, 0
Upvotes: 2
Reputation: 2240
def chain(*args):
for arg in args:
for item in arg:
yield item
a = [5, 8, 9]
b = [6, 1, 0]
for x in chain(a,b):
print x,
print ', '.join(map(str,chain(a,b)))
Upvotes: 3
Reputation: 250981
You could use itertools.chain
:
>>> from itertools import chain
>>> a = [5, 8, 9]
>>> b = [6, 1, 0]
>>> it=chain(a,b)
>>> for x in it:
print x,
...
5 8 9 6 1 0
Upvotes: 8