Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this python for loop increments my list?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading