BBedit
BBedit

Reputation: 8057

List index out of range, But I reset the index (Python)

I've been programming for about 1 week.

I'm writing a simple program to loop through this List and increment the variables by 1 each time.

I get the error: List index out of range.

I believe this is because my index value is too high? But I am resetting the index value before it goes too high with:

        index += 1
        index and 7

The logical AND should reset index to 0 once it becomes >= 8, shouldn't it?

In this case I don't understand what is wrong. Please see my code:

lookups = [0,1,2,3,4,5,6,7]
index = 0
dword_C06748 = 0

count = 0

offset1 = 0
rn_offset = 0


def next_value():
    global lookups, index, count
    while count < 18:
        lookups[index] += 1
        index += 1
        index and 7
        count += 1

next_value()

Upvotes: 0

Views: 2763

Answers (5)

tacaswell
tacaswell

Reputation: 87526

I think the following will replicate the output of your code in a more pythonic way:

lookups = [0,1,2,3,4,5,6,7]

def next_value():
    # xrange returns the value 0, 1, ... 17
    for count in xrange(18):   # or just range if you are using py3
        # the mod makes sure the index is always less than 8
        lookups[count % 8] += 1

next_value()

Upvotes: 1

rlms
rlms

Reputation: 11060

I would suggest you use either:

if index >= 8:
    index = 0

or

index = index % 8 

or an alternative using the inplace modulo operator

index %= 8

As it says in the Zen of Python (open a Python window and enter import this), readability counts. These options are much more readable than the corrected version of your code, using a bitwise and instead, therefore you should use them instead.

Upvotes: 1

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57680

index and 7 does not reset index. It just evaluates to a Boolean which is not saved. So this statement has not effect.

Use index = index % 8 instead. This ensures index will always be lower than 8.

Or you can use

 index = index % len(lookups)

Upvotes: 3

Anna
Anna

Reputation: 56

I think you want

&

rather than

and

Have a look at this resource: http://www.tutorialspoint.com/python/python_basic_operators.htm

And good luck learning :)

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251116

and is boolean AND in python, use & for bit-wise AND:

index &= 7  #index = index & 7

As integers are immutable, you should re-assign the result back to index.

Upvotes: 2

Related Questions