Frustrating alternate solution

Screen Link:

My Code:

values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 10, 14, 17, 14, 1, 16, 19, 7, 9, 19]
for num in values:
    if j is not int:
        j = 0
    j = values.index(num,j)
    values[j] = num + 1
print(values)

What I expected to happen: Loop through set of values, +1 to each value. The actual solution to the problem builds a new list using range(len(values)), I wanted to try and do it with just the values list.

The output works if j = 0 is declared outside the loop and the if: is removed from the loop, but then I have a variable floating around outside the loop which I don’t like:

j=0
for num in values:
    j = values.index(num,j)
    values[j] = num + 1

What actually happened: +2 on some values, +1 or 0 on others.

[18, 3, 8, 3, 21, 13, 6, 20, 2, 11, 11, 15, 17, 15, 2, 17, 20, 8, 10, 20]

Any advice? I think I’m struggling to get python to create j = 0 if j doesn’t already exist, but then I’m not really sure why the output is the way that it is.

Python won’t usually create a variable on its own if it doesn’t exist. You have to define/initialize it so that it can be used.

The code above results in the correct answer. Are you sure you are not running any other code other than the above?

Because I ran the code above and it returns the incremented values, so it is possible you are running some other code along with it as well.

If you don’t want to use range() then there aren’t many options left where you don’t use a variable like j as you have.

You could easily do something like -

j=0
for num in values:
    values[j] = num + 1
    j += 1

That’s an alternative to using index().

Later on, you will learn about enumerate() which is a better option than the above.

If you don’t use range() or enumerate() then you need to find a way to get the correct index to be able to update the corresponding item in the list. Using your approach of a variable like j is probably the only alternative then.

You could also create a separate new list and append the incremented numbers to that new list, and then save that new list to the values variable.

The code above results in the correct answer. Are you sure you are not running any other code other than the above?

Yeah - that’s what I said, the code works if j = 0 is declared outside the for loop. But I want to keep the for loop self-contained and declare j = 0 inside the for loop (like in the first code block in my initial post), but not set j = 0 each time it loops.

There are ways to do that, but those won’t be straightforward and would also likely be considered as bad programming practice.

Fair enough! I shall leave that alone then, rather than build a bad habit. Thanks for your help.

1 Like