Problem : Generator

Avi Gross avigross at verizon.net
Sat Feb 16 02:23:28 EST 2019


Just want to point out you can make any function into a generator by having
a yield statement like this:

>>> def previous(listing):
	while listing: yield listing.pop()

	
>>> for num in previous([1,2,3,4]): print(num)

4
3
2
1

The above is an EXAMPLE, not a particularly great way to do this. The point
is if you have an iterable you want to do reversed, you could do it without
an explicit reversal. Variations on the above that do not alter the list
would be to use an index based on the length of the list and count backward
as you return what is at that index. 

-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of dieter
Sent: Saturday, February 16, 2019 1:47 AM
To: python-list at python.org
Subject: Re: Problem : Generator

Prahallad Achar <acharbly at gmail.com> writes:

> I get list object instead gen  obj

If you have a list "l" and want a generator, you can use
   ( x for x in l)
or simpler "iter(l)" - which gives you an interator over "l".

An "iterator" is slightly more general than a generator (every generator is
also an iterator).




--
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list