This works just fine
list_a = [1,2,3,4,5,6,7,8,9,10]
for i in list_a:
for h in range(1,list_a[i]):
print(h)
but this does not work
months_b = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for i in months_b:
for h in range(1,months_b[i]):
print(h)
getting error
"for h in range(1,months_b[i]):"
"IndexError: list index out of range"
CodePudding user response:
On your first pass through the loop with months_b
your variable i
is set to the first value of the list, so 31. Then you iterate over the list from index 1 to 31 and there are not 31 elements of the list. Therefore, index out of range.
CodePudding user response:
for
variable
in
iterable
iterates over elements, not indices.
You want to use something like this:
for month in months:
for h in range(1,month):
print(h)
CodePudding user response:
range
is a list of natural numbers, in your case starting from 1 until months_b[i]
. Since your for
loop iterates over the elements of months_b
, your first i
will be 31. Therefore, your second loop will try to access the 31th element of months_b
, which is out of range.