Replace return
with yield
to turn your function into a generator function. When you call it, it returns a generator object that you can iterate over at your leisure to produce the results you want one at a time:
def listIterations(inputcsv):
for i in inputcsv:
yield str(i)
>>> listIterations(my_list)
<generator object listIterations at 0x00000237062CC350>
You will only be able to use this object once. Since your input is a list, you can always call listIterations
multiple times to get a new generator. To print, do a star-expand of the generator:
print(*listIterations(my_list), sep='\n')
Expanding the generator into an argument list will run it, and pass each element in to print
. If you want to have a permanent record of the generated values, expand them into a list:
generated_values = list(listIterations(my_list))
or a tuple:
generated_values = tuple(*listIterations(my_list))
You can print the stashed values the same way:
print(*generated_values, sep='\n')
All that being said, if you just need an iterator over a list, you can obtain one using the builtin iter
:
iter(my_list)
This is equivalent (for a list) to:
def listIterations(somelist):
yield from somelist
listIterations(my_list)