0

What is the use of yield and next function in python?

17th Feb 2019, 6:19 AM
Salman Ahmad
Salman Ahmad - avatar
4 Antworten
+ 3
yield() is used in generator functions, to push the next value of the series. Generators are similar to a list, but they can be very long or even infinite. Their benefit of a generator function, compared to a list comprehension, is that the next value is only calculated on demand, when you need it, not upfront for the whole series. This saves a lot of memory and processing time when you deal with large amounts of data. next() is used to cycle though the values of an iterator and get the next value (one at a time). You can iterate through lists, dictionaries, tuples and other iterable objects with the iter() function, which creates an iterator, then get the next value with next(). There is a chapter about generators in the python lessons: https://www.sololearn.com/learn/Python/2462/
17th Feb 2019, 10:00 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Examples. def itr(): lis = [] for a in range(1, 4): lis.append(a) return lis def itr2(): for a in range(1, 4): yield(a) Those two functions can be iterated the same way. for a in itr2(): print(a)
17th Feb 2019, 11:15 AM
Toni Isotalo
Toni Isotalo - avatar
+ 1
Thanks for the valuable information. Tibor Santa
17th Feb 2019, 10:49 AM
Salman Ahmad
Salman Ahmad - avatar
0
17th Feb 2019, 11:54 AM
Salman Ahmad
Salman Ahmad - avatar