Logo
Unit 6 – Generators

Generators

Duration: 5 minutes

Hello there, Python programmers on the move! Today, we’ll look at a terrific Python feature called “Generators.” They have a unique place in the Python world because of their capacity to create a series of outcomes over time rather than processing them all at once and returning them as a list. Intrigued? Let’s get started! Generators, like lists and tuples, are iterables. They don’t enable arbitrary indexing, unlike lists, although they can still be iterated through with **‘for’ **loops. They are made by combining functions and the **‘yield’ **keyword.

def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for number in count_up_to(5):
print(number)

In this example, **count_up_to** is a generator that yields numbers up to a limit. When the function is called in a **‘for’ **loop, it yields a value, then pauses its execution. It continues from where it left off each time it’s used again in the loop.

Exercise

Feeling the power of generators? Fantastic! Now, it’s your turn:- Create a generator that yields the squares of numbers up to a certain number.

  • Use this generator in a ‘for’ loop to print the squares.

Conclusion

Congratulations on mastering Python Generators! They are memory-saving tools that generate values on the fly rather than storing them in advance. Remember that understanding when to use which tool is the true art of programming. Continue researching, growing, and expanding your Python knowledge!

Next Tutorial: Regular Expressions

8 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!