Shriphani said:
If I have a function that loops over a few elements and is expected to
throw out a few tuples as the output, then what should I be using in
place of return ?
If it makes sense for the set of results to be returned all at once,
then return the object that collects them all together — a list of
tuples, for example.
If, instead, it makes sense for the results to be iterated over, you
can write a function that yields results one at a time, without
necessarily knowing in advance what the entire set will be::
... """ Yield numbers in the Fibonacci sequence
... to a maximum value of max_result. """
... prev_results = [0, 0]
... result = 1
... while result < max_result:
... yield result
... prev_results = [prev_results[1], result]
... result = sum(prev_results)
...
The function, when called, will return a generator object that you can
either iterate over::
... print n
...
1
1
2
3
5
8
13
21
34
55
89
or directly call its 'next' method to get one result at a time until
it raises a 'StopIteration' exception::
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration