obtaining multiple values from a function.
bignose+hates-spam at benfinney.id.au
Tue Sep 25 10:41:54 CEST 2007
Shriphani <shriphanip at gmail.com> writes:
> 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::
>>> def fib(max_result):
... """ 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, result]
... result = sum(prev_results)
The function, when called, will return a generator object that you can
either iterate over::
>>> fib_generator = fib(100)
>>> for n in fib_generator:
... print n
or directly call its 'next' method to get one result at a time until
it raises a 'StopIteration' exception::
>>> fib_generator = fib(5)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
\ "I have one rule to live by: Don't make it worse." -- Hazel |
`\ Woodcock |
More information about the Python-list