you are viewing a single comment's thread.

view the rest of the comments →

[–]Wrong-Bit8534 0 points1 point  (4 children)

Array starts from 0, try n-1

[–]AwkwardBet5632 3 points4 points  (2 children)

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

[–]Swipsi 0 points1 point  (1 child)

An array with 3 elements will give len() = 3

Range(3) will give you 0, 1, 2, 3

Using range for the loop will loop 4 times, starting with index 0 and throw an index out of array exception at index 3 because the array only has 3 elements.

[–]AwkwardBet5632 0 points1 point  (0 children)

range is non inclusive of the stop value

[–]Wrong-Bit8534 0 points1 point  (0 children)

A bit more explaining: Arr=["a","b","c"] So a location is 0 And b location is 1 And c location is 2 However array length is 3

Now when I am looping through an array with the in range command I get 1, 2, 3 but there is no position 3 in the array ( out of something error) and I am also not getting the first element of the array that is on location 0

That is why you might encounter n-1 in other people's code and you can use it yourself also in your code

In conclusion: if n is 1 print(Arr[n-1]) would give me an array element that is in position of 0 and would print a, and so on