[Tutor] List help...

Sean 'Shaleh' Perry shalehperry@attbi.com
Tue, 18 Jun 2002 20:53:14 -0700 (PDT)


first, please do not send html to mailing lists, not everyone wants to see html.

> How is the information stored as a list for the questions and
> answers? I don't get the form..a list inside a list. Then it took
> question_and_answer, and used [0] and [1] to get the values stored
> at the first and second positions in the list right? Basically -
> how is this structured to work the way it does? I can't seem to figure
> out how the answer and question are
> extracted... Thanks!

one of the best things about python is that you can run it interactively and
seek guidance directly from python itself.

$ python
>>> a_list = ['betty', 'veronica', 'sue']
>>> a_list
['betty', 'veronica', 'sue']
>>> len(a_list)
3
>>> a_list[0]
'betty'
>>> a_list[1]
'veronica'
>>> a_list[2]
'sue'
>>> a_list[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: list index out of range

In python a list is an indexed ordering of items.  The count starts at 0 and
goes to len(list) - 1.

A list can hold practically anything in python.  The example you had was
questions and answers.  Let's examine that now.

q_and_a = [['What is your name?', 'Sean'],
           ['What is your quest?', 'To seek the Holy Grail'],
           ['What is the air speed of a swallow?', 'African or European?']]

now, let's replace the questions and answers with numbers to make it easier to
see: [ [1,2], [3,4], [5,6] ].  As you can see we have here a list containing 3
lists.  So q_and_a[0] returns [1,2] in the numerical example or ['What is your
name?', 'Sean'] in the real example.

>>> q_and_a[0][0] # index the first item's first item
'What is your name?'
>>> q_and_a[0][1]
'Sean'

or

>>> block = q_and_a[0]
>>> block[1]
'Sean'

or

>>> answer = block[1]
>>> answer
'Sean'

or even

>>> question, answer = q_and_a[0]
>>> question
'What is your name?'
>>> answer
'Sean'

That last one translates as this:

(question, answer) = ['What is your name?', 'Sean']

and the first item goes to the first variable and the second to the second and
so on.

Hope this helps some.