[Tutor] Regular User defined functions Vs Generator functions

Alan Gauld alan.gauld at yahoo.co.uk
Sat Oct 31 04:50:52 EDT 2020


On 31/10/2020 01:38, Manprit Singh wrote:

> I have a question , why not to prefer generator functions instead of
> regular user defined functions, where i have problem like as that given
> below :

Any function that returns a potentially long sequence of values
is probably better written as a generator. It's just that from habit
most folks use return.  It's easy enough to convert a regular
function to a generator if it turns out that performance needs
it. But there's absolutely nothing wrong with doing it from
the beginning.

There may be a slight performance overhead in using a generator
where there are very low numbers of return values, but it's
minimal and as in any performance assessment you'd need to
measure it to determine whether the list or generator
approach worked best.

> def ind_word(st, w):
>     n = 0
>     while True:
>         n = st.find(w, n)
>         if n != -1:
>             yield n
>         else:
>             break
>         n += 1

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list