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.

0

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply, I accepted the oldest one because your solutions were similar.
Yes I was writing the textual part of the answer when he posted it.
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

Comments

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)]

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.