0

Can someone explain to me why this for loop doesn't work. I'm trying to use something like this in another program to loop through a list using this N as a parameter.

    N = [20,40,60,80]

    for j in N:
        print(j)
        for i in range(0,N[j]):
            print(i)

Thanks in advance!

7
  • what is your goal here? Commented Dec 6, 2017 at 2:45
  • why it doesn't work? what result do you expect ? Commented Dec 6, 2017 at 2:47
  • N is the number of balls bouncing around in a simulated box. The end goal is to calculate the pressure exerted under different temperatures with different numbers of balls. But for some reason I'm stuck on this seemingly simple list error Commented Dec 6, 2017 at 2:47
  • j is value from N, not index so you get N[80] but N doesn't so many elements. - use range(0, j) Commented Dec 6, 2017 at 2:47
  • @furas it tells me that "for i in range(0,N[j]):" is a IndexError: list index out of range Commented Dec 6, 2017 at 2:48

3 Answers 3

3

You're out of range, because j is taking the values of the elements of the N array, not the index. So, j is not 0, 1, 2, 3 but rather 20, 40, 60, 80. So, when you get to for i in range((0, N[j]), you're asking for N[20], which is well beyond the length of the N list.

You could do:

N = [20,40,60,80]

for j in range(len(N)):
#        ^^^^^^^^^^^^^
    print(j)
    for i in range(0,N[j]):
        print(i)
Sign up to request clarification or add additional context in comments.

1 Comment

Glad it helped. If you like my answer, please select it, and go back to studying! :)
0

you could use enumerate

N = [20,40,60,80]
for index, j in enumerate(N):
    print(j)
    for i in range(0,N[index]):
        print(i)

Comments

0

Try:

for i in range(0,j):

Instead of:

for i in range(0,N[j]):

Since N[j] will access way beyond whats in the list, such as N[80], which doesn't exist. This is why you're getting a IndexError: list index out of range error.

To fix this, you need to apply range() on your outer loop:

for i in range(len(N)):
    print(i)
    for j in range(0, N[i]):
        print(j)

Which only looks at the indexes i of N when applying it to range() in the inner loop, instead of the actual elements, which are a lot larger.

If you want to access whats actually in the list with respect to an index, try this:

N = [20,40,60,80]
for i in range(len(N)):
    print(i, "->", N[i])

Which outputs:

0 -> 20
1 -> 40
2 -> 60
3 -> 80

If you want just the numbers:

for number in N:
    print(number)

If you want both the index and the number in a more pythonic manner:

for index, number in enumerate(N):
    print(index, "->", number)

Which outputs:

0 -> 20
1 -> 40
2 -> 60
3 -> 80

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.