Basic question

Kirk Job Sluder kirk at jobspam/mapssluder.net
Sat May 12 17:40:03 EDT 2007


"Cesar G. Miguel" <cesar.gomes at gmail.com> writes:

> I've been studying python for 2 weeks now and got stucked in the
> following problem:
>
> for j in range(10):
>   print j
>   if(True):
>        j=j+2
>        print 'interno',j
>
> What happens is that "j=j+2" inside IF does not change the loop
> counter ("j") as it would in C or Java, for example.

Granted this question has already been answered in parts, but I just 
wanted to elaborate.

Although the python for/in loop is superficially similar to C and Java
for loops, they work in very different ways. Range creates a list
object that can create an iterator, and the for/in construct under the
hood sets j to the results of iterator.next().  The equivalent
completely untested java would be something like:

public ArrayList<Object> range(int n){
    a = new ArrayList<Object>; //Java 1.5 addition I think.
    for(int x=0,x<n,x++){
        a.add(new Integer(x));
    }
    return a;
}


Iterator i = range(10).iterator();

Integer j;
while i.hasNext(){
    j = i.next();
    system.out.println(j.toString());
    j = j + 2;
    system.out.println("interno" + j.toString());
}

This probably has a bunch of bugs.  I'm learning just enough java
these days to go with my jython.

1: Python range() returns a list object that can be expanded or
modified to contain arbitrary objects.  In java 1.5 this would be one
of the List Collection objects with a checked type of
java.lang.Object.  So the following is legal for a python list, but
would not be legal for a simple C++ or Java array.

newlist = range(10)
newlist[5] = "foo"
newlist[8] = open("filename",'r')

2: The for/in loop takes advantage of the object-oriented nature of
list objects to create an iterator for the list, and then calls
iterator.next() until the iterator runs out of objects.  You can do
this in python as well:

 i = iter(range(10))
 while True:
    try:
        j = i.next()
        print j
        j = j + 2
        print j
    except StopIteration:
        break

Python lists are not primitive arrays, so there is no need to
explicitly step through the array index by index. You can also use an
iterator on potentially infinite lists, streams, and generators.

Another advantage to for/in construction is that loop counters are
kept nicely separate from the temporary variable, making it more
difficult to accidentally short-circuit the loop.  If you want a loop
with the potential for a short-circuit, you should probably use a
while loop:

j = 0
while j < 10:
   if j == 5:
        j = j + 2 
    else:
        j = j + 1
    print j


>
> Am I missing something?
>
> []'s
> Cesar
>

-- 
Kirk Job Sluder



More information about the Python-list mailing list