Parsing lists

Alexander Williams thantos at chancel.org
Sun Jul 9 02:44:15 EDT 2000


On Sun, 09 Jul 2000 06:20:36 GMT, Seamus Venasse <python at polaris.ca> wrote:
>I am creating a simple list of titles and urls.  I would like to parse this
>list, but I keep receiving an error.  Here is a simplified version of my
>code and error received:
>
>>>> list = [ 'title1', 'url1', 'title2', 'url2', 'title3', 'url3' ]
>>>> for title, url in list:
>...     print title, url
>...
>Traceback (innermost last):
>  File "<stdin>", line 1, in ?
>ValueError: unpack sequence of wrong size
>
>Of course, if I change the code as follows, at least it prints everything in
>the list:
>
>>>> list = [ 'title1', 'url1', 'title2', 'url2', 'title3', 'url3' ]
>>>> for title in list:
>...     print title
>...
>title1
>url1
>title2
>url2
>title3
>url3
>
>What am I missing the first example?  Any assistance would be greatly
>appreciated.

Simple:

>>> for title, url in list:

is really:

>>> for (title, url) in list:

That is to say, the for loops over INDIVIDUAL ELEMENTS which are
tuples stored in the list named "list".  That said, the first ELEMENT
you get in the first case is "title1".  Obviously, that isn't a tuple,
so you get a sequence error.

The true fix for your problem is going to be changing the thing that
creates the list to use the format:

>>> list = [('title2', 'url2'), ('title2', 'url2'), ('title2', 'url2')]

This will work with your first loop above.

-- 
Alexander Williams (thantos at gw.total-web.net)           | In the End,
  "I think sex is better than logic,                    | Oblivion
   but I can't prove it."                               | Always
  http://www.chancel.org                                | Wins



More information about the Python-list mailing list