Working with Python yield, iter, next
Python's yield is a very useful keyword. It returns a value temporarily and pauses the function by preserving its state. There are methods like iter() and next() that work together with yield, and we will also learn try-except and Default Parameters.
Today's agenda:
- Iterables and Iterators
- Default Parameter (fallback value) and
try-exceptfor Error Handling- Difference between yield and return
- For Loop to use Generator
Iterables and Iterators
Python datatypes like lists, strings, tuples, dictionaries, sets, and ranges are called iterables. We use iterator iter(), a built-in function which returns the iterator object from iterables.
syntax:
iter(iterable) # iterator
next(iterator) # next valueWhen no values remain, next() raises StopIteration. For example:
arr = [1, 2] # arr contains 2 values, len(arr) == 3
next_number = iter(arr)
print(next(next_number)) # 1
print(next(next_number)) # 2
print(next(next_number)) # err -> StopIterationDefault Parameter (fallback value) and try-except for error handling
1. Default Parameter (fallback value)
To handle the StopIteration error we can use a fallback value directly in the next() method. This is an easier and more effective way than writing a try-except block.
syntax:
next(iterator, 'finished') # 'finished' string as a fall back value 2. try-except
We can use try-except to handle the StopIteration error.
# syntax:
try:
next(iterator)
except StopIteration:
pass # handle your error hereCombined Example
arr = [1, 2] # arr contains 4 values, len(arr) is 4
next_number = iter(arr)
print(next(next_number)) # 1
print(next(next_number)) # 2
# Fall back example
print(next(next_number, 'no more item on arr')) # 'no more item on arr'
# try-except example
try:
print(next(next_number)) # error
except StopIteration:
print('no more item on arr') # 'no more item on arr'Difference between yield and return
The return keyword is very commonly used while writing functions. After writing a block of code and applying logic inside the function, it simply returns the result using the return keyword. After the return line, other lines of code are not accessible.
# Uses of return
def next_number():
numbers = [1,2,3]
for number in numbers:
return number # Always returns the first number -> 1
print('this line will never execute')
print(next_number()) # 1
print(next_number()) # 1
# next_number() always generates 1 in this caseyield is a keyword like return that provides the current result and can also preserve the function state, which means another call can reuse the same state to get another result.
# Uses of yield
def next_number():
numbers = [1,2,3]
for number in numbers:
print('Starting number')
yield number
print('Ending number')
which_number = next_number() # Generator function (Function that contains the yield keyword)
print(next(which_number)) #Output: 1
print(next(which_number)) #Output: 2
print(next(which_number)) #Output: 3Here, each next() call resumes the function until the next yield.
For Loop to use Generator
To extend the above example, we can use a for-in loop instead of next() to get the same results.
# Uses of yield
def next_number():
numbers = [1,2,3]
for number in numbers:
print('Starting number')
yield number
print('Ending number')
which_number = next_number() # Generator function
for number in which_number:
print(number)