Explanation about for

Chris Rebert clp2 at rebertia.com
Mon Jan 9 18:58:41 EST 2012


On Mon, Jan 9, 2012 at 3:23 PM, Νικόλαος Κούρας <nikos.kouras at gmail.com> wrote:
> ================================
> dataset = cursor.fetchall()
>
> for row in dataset:
>    print ( "<tr>" )
>
>    for item in row:
>        print ( "<td><b><font color=yellow> %s </td>" % item )
> ================================
>
> and this:
>

Your second snippet makes use of Python's
iterable/sequence/tuple-unpacking feature. Here's the relevant part of
the Language Reference:
http://docs.python.org/reference/simple_stmts.html#assignment-statements

By way of example, given:
seq = [1,2,3,4]
Then:
w, x, y, z = seq
Results in:
w = 1
x = 2
y = 3
z = 4
`seq` has been "unpacked", and its elements have been assigned to
variables (namely: `w`, `x`, `y`, and `z`). If the number of variables
doesn't match the number of elements, Python will raise an exception.

> ================================
> dataset = cursor.fetchall()
>
> for host, hits, agent, date in dataset:

for-loops perform repeated assignments to the loop variable(s), and,
like with the simple assignment statement example I gave, also permit
the use of unpacking in such assignments. To make the unpacking more
explicit, the loop can be equivalently rewritten as:
for _row in dataset:
    host, hits, agent, date = _row
    # rest same as before...

>    print ( "<tr>" )
>
>    for item in host, hits, agent, date:

Python's syntax for tuples is based solely on commas and does not
require parentheses, though a tuple's repr() always includes the
parentheses and programmers often/typically do too. (See
http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences
.) For example:
x = 1, 2
And:
x = (1, 2)
Both do exactly the same thing: set `x` to a tuple of length 2
containing the elements 1 and 2.
The loop thus might be more clearly written as:
    for item in (host, hits, agent, date):
So, what's happening is that Python is iterating over the elements of
an anonymous literal tuple; `item` will thus take on the values of
`host`, `hits`, `agent`, and `date`, in turn.

>        print ( "<td><b><font color=white> %s </td>" % item )
> ================================

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list