3

Is it possible to manipulate the index pointer in a Python for loop?

For example in PHP the following example will print 1 3:

$test = array(1,2,3,4);
for ($i=0; $i < sizeof($test); $i++){
    print $test[$i].' ';
    $i++;
}

However in Python there is no effect when I try to increment the index. For example the following will print all the numbers:

test = ['1', '2', '3', '4']
for i in xrange(len(test)):
  print test[i]
  i=i+1

Is there a way to manipulate the for loop pointer inside the loop so I can implement some complex logic (e.g. go back 2 steps and then forward 3)? I know there may be alternative ways to implement my algorithm (and that's what I do at the moment) but I'd like to know if Python offers this ability.

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Vasilis
  • 2,721
  • 7
  • 33
  • 54

4 Answers4

9

When you try to manipulate the index i you are doing it, but when the for loop goes to the next iteration, it assigns to i the next value of xrange(len(test)) so it won't be affected by the manipulation you did.

You may want to try a while instead:

test = ['1', '2', '3', '4']
i = 0
while i < 4:
    print test[i]
    i += 2
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
6

Yes and no. The python loop is meant to iterate over a predefined iterator and thus does not directly allow modifying its progress. But you can of course do the same as in php:

test = ['1', '2', '3', '4']
i = 0
while i < len(test):
    print test[i]
    # Do anything with i here, e.g.
    i = i - 2
    # This is part of the loop
    i = i + 1
Chronial
  • 66,706
  • 14
  • 93
  • 99
1

For complex loop logic, you can set the step size to iterate over the array you create or use a lambda function.

#create an array
a = [3, 14, 8, 2, 7, 5]

#access every other element

for i in range(0, len(a), 2):
    print a[i]

#access every other element backwards

for i in range(len(a) - 1, 0, -2):
    print a[i]

#access every odd numbered index

g = lambda x: 2*x + 1
for i in range(len(a)):
if g(i) > len(a):
        break
else:
        print a[g(i)]
Jesuisme
  • 1,805
  • 1
  • 31
  • 41
0

The semantic of for is

iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object

You could read more about for here.

So if you want to implement some logics when visiting a container, you should use while or other methods rather than for.

flyer
  • 9,280
  • 11
  • 46
  • 62