Reputation: 39
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!
Upvotes: 0
Views: 7056
Reputation: 26335
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
Upvotes: 0
Reputation: 766
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)
Upvotes: 0
Reputation: 5699
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)
Upvotes: 3