How to join two generators in Python?

Homer Xing picture Homer Xing · Jul 9, 2010 · Viewed 83.2k times · Source

I want to change the following code

for directory, dirs, files in os.walk(directory_1):
    do_something()

for directory, dirs, files in os.walk(directory_2):
    do_something()

to this code:

for directory, dirs, files in os.walk(directory_1) + os.walk(directory_2):
    do_something()

I get the error:

unsupported operand type(s) for +: 'generator' and 'generator'

How to join two generators in Python?

Answer

Philipp picture Philipp · Jul 9, 2010

I think itertools.chain() should do it.