0

I'm having trouble with my loops. I get an error for 400 being out of range. Am I applying something that is not allowed, or what is my issue? It looks like legal syntax to me?

survTime=np.array([400, 800, 1100, 900])
age=np.array([40, 40, 40, 40])
counter_1yr=0
counter_2yr=0
counter_3yr=0
n=1
for i in survTime:
     for j in age:
        if survTime[i] > 365 and age[j] < 50:
            counter_1yr+=1
            n+=1
            continue
        elif survTime[i] > 730 and age[j] < 50:
            counter_2yr+=1
            n+=1
            continue
        elif survTime[i] > 1095 and age[j] < 50:
            counter_3yr+=1
            n+=1
            continue
print("1 year probability: ", counter_1yr/n)
print("2 year probability: ", counter_2yr/n)
print("3 year probability: ", counter_3yr/n)
2
  • 1
    for i in survTime does not give you a counter from 0 -> len(survTime) it gives you the actual values of survTime one by one. You do not need to access the arrays by index after that. The way you are doing it, one the first loop will yield the call if survTime[400] > 365 and age[40] < 50: - which is clearly out of range. You can just do if i > 365 and j < 50: Commented Nov 16, 2017 at 17:33
  • 1
    Possibly a manifestation of the XY problem. Try to ask about the original problem X you are trying to solve instead of asking about how to implement the solution Y you conceived (it is OK to show what you have tried so far). Commented Nov 16, 2017 at 17:33

2 Answers 2

5

You're confusing values with indexes. In Python, the for x in ... syntax returns each of the elements in an iterable object, not the indexes. Try this instead:

for t in survTime:
     for a in age:
        if t > 365 and a < 50:
        # and so on

Notice that you intended to iterate over the values of each array, but in reality you're using each item as an index, which is way out of bounds - for instance: survTime doesn't have 400 elements! For completeness' sake: if you really needed the indexes, the way to traverse a list called lst would be:

for i in range(len(lst)):
    ele = lst[i] # do something with the element
Sign up to request clarification or add additional context in comments.

Comments

2

for in enables you the iterate over items, not index. I would guess you want to have

for i in survTime:
    for j in age:
        # now i == survTime[0] and j == age[0]
        if i > 365 and j < 50:
            # more code

Or if you want to work with index, use for i in range(len(survTime))
Or if you want to work with both, use for index, value in enumerate(survTime)

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.