+ 2

What is diffrence between return and yield statements?

plz give onr example..

9th Jul 2018, 7:09 AM
lokesh reddy
lokesh reddy - avatar
4 ответов
+ 2
def _yield(): for x in range(10): yield x def _return(): l = [] for x in range(10): l.append(x) return l yield_ = _yield() print(yield_) print(next(yield_)) print(list(yield_)) return_ = _return() print(return_) # https://www.quora.com/What-is-the-difference-between-yield-and-return-in-JUMP_LINK__&&__python__&&__JUMP_LINK
9th Jul 2018, 1:29 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 3
Simply, the yield function will return a genarator item instead of returning the whole list (look up on generator where it can be used for other iteration method). This is mainly used for saving memory space especially for when a large amount of data is being handled. For instance, def create_list(x): list = [] for i in range(x): list.append(i) return list def create_gen(x): for i in range(x): yield i where both functions can both be used in for loops eg. for i in create_gen(4): print(i) or for i in create_list(4): print(i) which give the same result >>> 0 1 2 3 >>> the create_list(x) will take up the amount of space based on the length of the list returned, whereas the create_gen(x) will return a generator where it will only take up the space of each item generated. NB: I am not a professional myself. If there is anything wrong here, I am very sorryy~ T-T https://pythontips.com/2013/09/29/the-JUMP_LINK__&&__python__&&__JUMP_LINK-yield-keyword-explained/
10th Jul 2018, 12:44 AM
KuriKuRa
KuriKuRa - avatar
+ 1
tqs
9th Jul 2018, 1:56 PM
lokesh reddy
lokesh reddy - avatar
0
tqs...
10th Jul 2018, 5:56 PM
lokesh reddy
lokesh reddy - avatar