Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a generator from two lists in python?

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
like image 766
Bovard Avatar asked Dec 21 '22 06:12

Bovard


2 Answers

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
like image 157
Ashwini Chaudhary Avatar answered Dec 22 '22 20:12

Ashwini Chaudhary


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)))
like image 42
Hal Canary Avatar answered Dec 22 '22 20:12

Hal Canary