obtaining multiple values from a function.

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Sep 25 04:41:54 EDT 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[1], 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
    ...
    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::

    >>> fib_generator = fib(5)
    >>> fib_generator.next()
    1
    >>> fib_generator.next()
    1
    >>> fib_generator.next()
    2
    >>> fib_generator.next()
    3
    >>> fib_generator.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration

-- 
 \        "I have one rule to live by: Don't make it worse."  -- Hazel |
  `\                                                          Woodcock |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list