-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
40 lines (28 loc) · 1.01 KB
/
Copy pathmain.py
File metadata and controls
40 lines (28 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# A Python generator is a special kind of function that lets you produce a sequence of values lazily — meaning it generates each value only when needed
# instead of building the entire list in memory.
# This makes generators great for:
# Handling large datasets without memory issues
# Creating infinite sequences
# Writing cleaner, more readable code compared to manual iteration logic
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
gen = count_up_to(3)
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3
try:
next(gen)
except StopIteration:
print("StopIteration")
# When Python sees a yield:
# It pauses the function and returns a value.
# The function’s internal state is saved (local variables, instruction pointer).
# When you call next() again, execution resumes right after the yield.
# Generator Expressions
# Short form of generators:
gen = (x*x for x in range(5))
# List comprehension → makes a full list
# Generator expression → generates lazily