Iterators in Python

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 &l…


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


Print Share Comment Cite Upload Translate Updates
APA

RocketMaker69 | Sciencx (2021-10-16T18:18:18+00:00) Iterators in Python. Retrieved from https://www.scien.cx/2021/10/16/iterators-in-python/

MLA
" » Iterators in Python." RocketMaker69 | Sciencx - Saturday October 16, 2021, https://www.scien.cx/2021/10/16/iterators-in-python/
HARVARD
RocketMaker69 | Sciencx Saturday October 16, 2021 » Iterators in Python., viewed ,<https://www.scien.cx/2021/10/16/iterators-in-python/>
VANCOUVER
RocketMaker69 | Sciencx - » Iterators in Python. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/16/iterators-in-python/
CHICAGO
" » Iterators in Python." RocketMaker69 | Sciencx - Accessed . https://www.scien.cx/2021/10/16/iterators-in-python/
IEEE
" » Iterators in Python." RocketMaker69 | Sciencx [Online]. Available: https://www.scien.cx/2021/10/16/iterators-in-python/. [Accessed: ]
rf:citation
» Iterators in Python | RocketMaker69 | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.