Code Explanation:
1. Define Generator Function
def squares():
This defines a generator function named squares.
2. Loop Through Range
for i in range(1, 4):
yield i*i
range(1, 4) → generates values 1, 2, 3.
For each i, it yields i*i, which are the squares of 1, 2, and 3:
Yields: 1, 4, 9
3. Create Generator Object
s = squares()
Calls the generator function → returns a generator object.
Nothing runs yet—it's lazy and only runs when iterated over.
4. Convert Generator to List
print(list(s))
This exhausts the generator, converting all yielded values into a list.
Internally, it calls next(s) until the generator is finished.
The result is:
[1, 4, 9]
Final Output:
[1, 4, 9]
.png)

0 Comments:
Post a Comment