List of lists

Ben Finney bignose-hates-spam at and-zip-does-too.com.au
Thu Jun 26 23:14:53 EDT 2003


On Fri, 27 Jun 2003 03:15:56 GMT, Mike wrote:
> def get_questions():
>     return [["What color is the daytime sky on a clear day?","blue"],\
>                ["What is the answer to life, the universe and
> everything?","42"],\
>                ["What is a three letter word for mouse trap?","cat"]]

These should not be a list of lists.  To refer to a previous c.l.python
discussion, "for homogeneous data, use a list; for heterogeneous data,
use a tuple".

Thus, each question-and-answer pair is heterogeneous: it matters which
is which, and which position each is in; and extending it with more
items doesn't have any meaning.

On the other hand, a list of question-and-answer pairs is homogeneous:
each can be treated like any other question-and-answer pair, and the
list of them could be indefinitely extended or contracted without
distorting the meaning of the list.

So, get_questions() is better done with:

    def get_questions():
        return [
            ( "What colour is a clear daytime sky?", "blue" ),
            ( "What is the answer to the ultimate question?", "42" ),
            ( "What is a three-letter word for mouse trap?", "cat" ),
        ]

(Note that placing a comma even after the last item in a list, allows
you to extend the list in the code without having a missing comma by
accident.)

Then, you iterate over the list of question-and-answer pairs, and get a
tuple of (question, answer) each time:

    >>> for (question, answer) in get_questions():
        print question, answer

    What colour is a clear daytime sky? blue
    What is the answer to the ultimate question? 42
    What is a three-letter word for mouse trap? cat

-- 
 \     "Homer, where are your clothes?"  "Uh... dunno."  "You mean Mom |
  `\   dresses you every day?!"  "I guess; or one of her friends."  -- |
_o__)                                     Lisa & Homer, _The Simpsons_ |
http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B




More information about the Python-list mailing list