+ 1
what's yield in python? please give me examples code
6 Antworten
+ 10
Return returns a concrete value while yield constructs a generator, which when called returns consecutive (in the iterative sense) values.
Generators are cool because they don't create an instance of an iterator (like list or tuple, which when initiated, take up all needed memory) and so are memory-efficient. They can be understood as a scheme of returning values consecutively when called.
However, because they do not create "instantiated" iterators, they for example cannot be indexed -- you cannot call its x-th element right away.
+ 4
[meta, okay to ignore]
A concrete way that I look at the generator/yield pattern is that I can pause an infinite algorithm like: sqrt(2), PI or the Fibonacci sequence--report what I know so far--then resume as if there was no interruption.
In some languages (like Javascript) you can even change the generator's operation in the "algorithm is paused" time between the last yield and the next request.
[very meta]
SQL server query results are often returned using the generator...yield pattern because:
"I don't want 1,000,000 rows back right now, I want 100 now, then another 100 in a minute..." (etc)
+ 3
Yield defines a generator, a kind of a "multiple, iterative return" :)
Refer to this lesson below:
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2462/?ref=app
+ 1
thank you
+ 1
comparing yield and return statements:
return: returns one single object and terminates the function call.
yield: returns an iterator object, which is little similar to list, it can be used in for loops, but can not be indexed, to be able to index them you need to convert them to lists or tuples with list() or tuple() function. Yield doesn't terminate the function call.
0
i see this post and dont understand. whats different return and yield?