r/PythonLearning • • Aug 17 '25

What's wrong

Post image
49 Upvotes

45 comments sorted by

View all comments

3

u/earchip94 Aug 17 '25 edited Aug 18 '25

Length of a list/array/etc is not a valid index for that object. Because it is 0 indexed you at a minimum need to subtract 1 from the length. Range syntax and usage is valid. Max value of range(n) is n-1.

Edited for clarity.

2

u/AwkwardBet5632 Aug 17 '25

range(n) goes from 0 to n-1.

2

u/HotLaMon Aug 17 '25

range(n)

What is n?
n = len(l)
What is the length of l? 5
n = 5

print(l[n]) = print(l[5])
What is the element at index 5? Nothing. Out of range error.

range(n) going from 0 to n-1 has nothing to do with the fact that OP is trying to access an index that doesn't exist.

0

u/AwkwardBet5632 Aug 17 '25

Yes, and OP’s error has nothing to do with the comment I was replying to, which it claiming a problem with the range.

2

u/earchip94 Aug 18 '25

Wasn’t stating it was an issue with the range. Was stating it’s an issue with their usage of n. I see how that could’ve been more clear in my first comment.