r/PythonLearning • • Aug 17 '25

What's wrong

Post image
49 Upvotes

45 comments sorted by

View all comments

2

u/denehoffman Aug 17 '25

Try printing l[i]and also print i on each iteration and you’ll quickly see the problem. Array indices start at 0, so the last index is n-1. range(n) starts at 0 by default and does not include the upper bound. Also try print(list(range(n))) to see what I mean! Print statements are your friend, your other friend is a debugger, but that’s more complicated.

9

u/coopsoup247 Aug 17 '25 edited Aug 17 '25

In addition, the script can also be shortened to this:

l=[9,2,3,6,5]
for i in l:
    print(i)

EDIT: cleaned up the formatting

2

u/ilidan-85 Aug 17 '25

It can but it doesn't mean it should. We should write readable code for ourselves in future and others. Clean, readable code is gold!

2

u/coopsoup247 Aug 17 '25

My bad. I wrote it on my phone and it didn't format correctly. I've fixed it now.