why does this for loop increments the integers on my list? I really don’t understand, I’m new to python.
Thank you.
testlist = [1,4,2,4,3,4,4,4,4,5]
for x in testlist:
print(testlist[x])
Output:
4
3
2
3
4
3
3
3
3
4
4
Expected:
1
4
2
4
3
4
4
4
4
5
>Solution :
you’ll want to change that to
testlist = [1,4,2,4,3,4,4,4,4,5]
for x in testlist:
print(x)
this is because x is being made equal to testlist[loopcounter] so its thinking when loopcounter = 1 it should read the value at testlist[1] which is 4 and then print the value of testlist[4]
apologies for any formatting issues