python - Difference between function and generator? -
i reviewed question difference between function , generator? marked duplicate. posting version of answer here.
the original question was:
i looking exact difference between normal function , generator. have googled it. results quite confusing. beginner, expecting short , precise example.
i tried what difference between normal function , generator function? not use.
i have gone through what "yield" keyword in python? purely talking generator, there nothing difference between function , generator. need help?
in principle generators memory efficient lazy evaluation.
a generator similar function returns array, in generator has parameters, can called, , generates sequence of values. however, instead of building array containing values , returning them @ once, generator yields
values 1 @ time, requires less memory , allows caller started processing first few values immediately.
in short, generator looks function
behaves iterator
.
from itertools import count
itertools
provide count
generate infinite stream of integer. can give start , step tell starting , stepping value generated stream. going use in following example.
for in count(start=0, step=1): print
a simple example generate list of numbers.
build , return list:
def find_even_number_function(number_stream): even_number = [] n in number_stream: if n % 2 == 0: even_number.append(n) return even_number in find_even_number_function(count()): print
the code quite simple , straightforward, builds full list in memory. not acceptable in our case, because cannot afford keep infinite integers in memory. can see function never stop. in case going use generator.
a generator yields
items instead of returning list
def find_even_number_generator(number_stream): n in number_stream: if n % 2 == 0: yield n in find_even_number_generator(count()): print
note expression of number generation logic clear , natural. similar implementation built list in memory, has memory usage characteristic of iterator implementation.
the performance improvement use of generators result of lazy (on demand) generation of values, translates lower memory usage. furthermore, not need wait until elements have been generated before start use them. similar benefits provided iterators, generator makes building iterators easy.
so in simple words, if use normal function above case, run out of memory. alternatively if use generator function run out of time.
Comments
Post a Comment