Explanation about for

Ian Kelly ian.g.kelly at gmail.com
Mon Jan 9 18:42:22 EST 2012


2012/1/9 Νικόλαος Κούρας <nikos.kouras at gmail.com>:
> ================================
> dataset = cursor.fetchall()
>
> for row in dataset:
>    print ( "<tr>" )
>
>    for item in row:
>        print ( "<td><b><font color=yellow> %s </td>" % item )
> ================================
>
> and this:
>
> ================================
> dataset = cursor.fetchall()
>
> for host, hits, agent, date in dataset:
>    print ( "<tr>" )
>
>    for item in host, hits, agent, date:
>        print ( "<td><b><font color=white> %s </td>" % item )
> ================================
>
>
> Can you please explain me how the for structure works here?

You should probably read through the Python tutorial or a Python book
for the basics of Python for loops.

> a) In the 1st example we have 'for row in dataset' what is the value
> of 'row' at that time? What part of 'dataset' is 'row'?

dataset is an iterable object, which means that Python can ask it for
an iterator and then use that iterator to "loop" through the dataset
in some fashion.  In this case, 'dataset' is a database cursor, and
the values returned by the iterator are the rows that were selected by
the query that executed, represented as tuples.  'row' takes on the
value of each of those tuples, one at a time.

> b) In the 2nd example we have for 'host, hits, agent, date in
> dataset'. How does these 4 variables take their values out of dataset?
> How dataset is being splitted?

The second example works the same way as the first, except that
instead of storing each row tuple in a single variable called row, it
unpacks each tuple into four different variables named 'host', 'hits',
'agent', and 'date'.  These represent the values of the selected
columns from the query, for each selected row.

HTH,
Ian



More information about the Python-list mailing list