a couple of things I don't understand wrt lists

John Gordon gordon at panix.com
Tue Apr 16 12:43:23 EDT 2013


In <mailman.668.1366126626.3114.python-list at python.org> aaB <mecagonoisician at gmail.com> writes:

> but when I do:

> for i in rule:
>   print rule[i]

> I get the "complement":
> 1
> 1
> 1
> 1
> 0
> 1
> 1
> 1

When you iterate over a list with this statement:

    for i in rule:

i contains each successive list item.

However, your code:

    print rule[i]

acts as though i is the list item's *subscript*, which is incorrect.
In effect, your code is doing this:
    print rule[0]
    print rule[0]
    print rule[0]
    print rule[0]
    print rule[1]
    print rule[0]
    print rule[0]
    print rule[0]

Although in your example both rule[0] and rule[1] are zero, so I
don't know why '1' ever got printed.

Also, as far as I can tell, this code should not have worked at all:

    for i in range(rule):
        print rule[i]

The range() function expects an integer, not a list.

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list