Is there a clean "Pythonic" way to write an input-replacement function in Python that will yield a value from a predetermined list of input values each time it's called?
raw_data = ['8', '2', '1']
c = 0
def input():
global c
c += 1
return raw_data[c - 1]
for _ in range(3):
print(input())
This does and is expected to output:
8
2
1
Intuitively yield seems like it ought to be part of the solution but I cannot wrap my head around how to implement it as an input replacement.
yieldinstead ofreturn, you don't needcto be global.def input_replacement(): c = 0; while True: yield raw_data[c]; c += 1. Perhaps the thing you were missing was the necessity to have an explicit loop in the function that usesyieldinput()returns a generator iterator instead of a value.def source_of_input(): ...yield...and theninput = source_of_input()or something.