Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to python generators

Tags:

Is it possible to append elements to a python generator?

I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator. Any help would be much appreciated.

Related:

  • Flattening a shallow list in python
like image 650
Francisco Avatar asked Feb 21 '09 01:02

Francisco


People also ask

What additional methods do generator objects have?

Generator objects have two additional methods, return() and throw() , that are similar to next() .

What can you do with a generator object Python?

Python provides a generator to create your own iterator function. A generator is a special type of function which does not return a single value, instead, it returns an iterator object with a sequence of values. In a generator function, a yield statement is used rather than a return statement.

Are generators lazy in Python?

Generators are memory efficient since they only require memory for the one value they yield. Generators are lazy: they only yield values when explicitly asked.


1 Answers

You are looking for itertools.chain. It will combine multiple iterables into a single one, like this:

>>> import itertools  >>> for i in itertools.chain([1,2,3], [4,5,6]): ...     print(i) ...  1 2 3 4 5 6 
like image 61
dF. Avatar answered Sep 23 '22 22:09

dF.