looping through a list
Sean 'Shaleh' Perry
shalehperry at attbi.com
Fri Apr 26 22:14:12 EDT 2002
>
> result = c.fetchone()
> if (result != ""):
> i=0
> text = '<tr width = "80%" align = "center">'
> while (i != len(result)+1):
> i = i + 1
> text = text + '<td align = "center" valign =
> "top">'+str(result[int(i)]) +'</td>'
> text = text + "</tr>"
> page.generate("","",sessionID,text)
> else:
> text = '<h4>No items found</h4>'
> page.generate("","",sessionID,text)
>
>
> At the moment, it keeps saying list index out of bounds and I don't
> know where I'm going wrong. I've tried all sorts of things in the
> While statement and still can't get it going.
>
In python you almost never want to use a counting loop. The above is better
written as:
for piece in result:
text = text + '<td align="center" valign="top"> + piece + '</td>'
the string append is slow, so this:
table_entries = []
for piece in result:
tables_entries.append('<td align="center" valign="top">%s</td>' % piece)
text = string.join(tables_entries, '')
will work better still. Although you may find the first version more readable.
More information about the Python-list
mailing list