2

Based on an element found in a list, I'd like to update the index value in my for loop. I believe I've done this, but my Python script doesn't seem to be outputting the correct values and I cannot figure out why:

My list looks like this:

dataXY = [['6', 'c', '3', '7', '2', '9', '1', '7'],['8', '4', 'c', '7', '9', '3', '4', '7', '1', '2']]

And my code that works on this is:

for lists in dataXY:
    XYbezier = []
    final_lists = []
    for datum in range(len(lists)):
        if lists[datum] == 'c':
            for k in range(-1,4):
                if k != 0:
                    XYbezier.append(lists[datum+k])
        else:
            if lists[datum-1] == 'c':
                datum += 3
                if datum != len(lists):
                    final_lists.append(lists[datum])
            else:   
                final_lists.append(lists[datum])
    print datum

What it's printing is this: 1 5 3 4 5 6 7 0 1 2 6 4 5 6 7 8 9

For some reason, the index value is being reset, but then restored (from how it skips to 5 from 1 and then goes back to 3) I don't understand why it's doing this, and I need the index value to jump 3 places and permanently update instead of restoring itself back to its original value.

1
  • In plain English - what is this supposed to do? Commented May 5, 2013 at 14:09

2 Answers 2

1

When you use a for loop, the index variable is loaded from values in a list. range(x) creates the list [0,1,2, ... ,x] so on each iteration, datum (in your case) gets a new numerical value off that list. This overrides any value that datum may hold.

You can accomplish your goal by switching to a while loop:

datum = 0
end = len(lists)
while datum < end:
    # do stuff

    # don't forget to increment datum
    datum += 1
Sign up to request clarification or add additional context in comments.

Comments

0

Use a while loop:

datum=0
while datum < len(lists):

In a for-loop the value of datum will be automatically reset to the next value from the range as soon as the loop begins again. Though a while loop will not update datum automatically like for-loop does, you'll have to increase it yourself, otherwise your code will stuck in an infinite loop.

2 Comments

Does that syntax… work? And could you explain why what the OP tried didn’t?
Now shouldn’t it be while datum < len(lists)?

Your Answer

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