Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: convert list to generator

Tags:

python

Say I have a list

data = [] data.append("A") data.append("B") data.append("C") data.append("D") 

How do I convert this to a generator? Any help with sample code would be highly appreciated...

Found a URL: http://eli.thegreenplace.net/2012/04/05/implementing-a-generatoryield-in-a-python-c-extension/

Is this what I want to do?

like image 266
swordholder Avatar asked Apr 16 '13 15:04

swordholder


People also ask

How do you convert a list into iterable in Python?

Use the __iter__() and __next__() Method to Convert Object to Iterator in Python. As the name suggests, an iterator returns the data values one by one. The iterator object does this with the help of the __iter__() and the __next__() method. The __iter__() and __next__() method together form the iterator protocol.

How do you turn a list into an iterator?

To make an array iterable either you need to convert it to a stream or as a list using the asList() or stream() methods respectively. Then you can get an iterator for these objects using the iterator() method.

Can I convert a list to a string Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


2 Answers

Are you sure, you want to create a generator? A generator is function which returns an iterator type, constructed e.g. by using the yield keyword (cf. term-generator). If you really want this, steven-rumbalski's answer is precisely what you are looking for:

data_gen = (y for y in data) 

Most of the time, you will want to directly create an iterator object, e.g. to use the next() method. In this case, the answer is implicit in the comment by mgilson above:

data_iter = iter(data) 

which is equivalent to data_iter = data.__iter__(), cf. functions#iter.

like image 66
Heinrich Hartmann Avatar answered Sep 29 '22 02:09

Heinrich Hartmann


>>> (n for n in [1, 2, 3, 5]) <generator object <genexpr> at 0x02A52940> 

works in Python 2.7.4+

>>> a2g = lambda x : (n for n in x) >>> a2g([1, 2, 3, 4, 5]) <generator object <genexpr> at 0x02A57CD8> 

Edit:

One more slight variation of a lambda generator factory pattern

>>> a2g = lambda *args: (n for n in args) >>> for i in a2g(1, 2, 3, 4, 5): print i  1 2 3 4 5 
like image 30
David Avatar answered Sep 29 '22 01:09

David