This content originally appeared on DEV Community and was authored by RocketMaker69
Hi guys, i'm back! So today we will discuss about iterators, which are functions that yield values. The yield keyword is like return, but it doesn't end the function. Here's an example:
def <function_name>(<args>):
# ...
yield <something>
replacing the placeholders:
def sq(x):
for i in range(1, x+1):
yield i ** 2
To call the iterator methods, do this:
for <something> in <method_name>(<args>):
<code>
And here is a full example:
def sq(x):
for i in range(1, x+1):
yield i ** 2
for i in sq(10):
print(i)
"""
1
4
9
16
25
36
49
64
81
100
"""
With that, Goodbye guys! Have a nice day!
This content originally appeared on DEV Community and was authored by RocketMaker69
RocketMaker69 | Sciencx (2021-10-16T18:18:18+00:00) Iterators in Python. Retrieved from https://www.scien.cx/2021/10/16/iterators-in-python/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.