Parsing lists

Paul Prescod paul at prescod.net
Sun Jul 9 02:33:02 EDT 2000


Seamus Venasse 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
> 

The for loop does not "parse" or do anything else very intelligent with
the list. It merely loops over all of the items. There is no way to make
it do what you want it to do. 

You should probably change your data structure to be a list of pairs or
objects. If you can't do that directly, this function will probably
help:

>>> def pairList( thelist ):
...     newlist=[]
...     for i in xrange( 0, len( thelist ), 2 ):
...         newlist.append( (thelist[i], thelist[i+1]) )
...     return newlist
...
>>> list = [ 'title1', 'url1', 'title2', 'url2', 'title3', 'url3' ]
>>> list=pairList( list )
>>> list
[('title1', 'url1'), ('title2', 'url2'), ('title3', 'url3')]
>>> for title,url in list:
...     print title, url
...
title1 url1
title2 url2
title3 url3

-- 
 Paul Prescod - Not encumbered by corporate consensus
"Computer Associates is expected to come in with better than expected 
earnings." Bob O'Brien, quoted in
	- http://www.fool.com/news/2000/foth000316.htm




More information about the Python-list mailing list