Why do indexes start at zero in the likes of Python?

All sorts of amusements and nonsense unrelated to xTalk
Post Reply
Skids
Posts: 106
Joined: Thu Dec 22, 2022 9:40 am
Location: North Lincolnshire
Contact:

Why do indexes start at zero in the likes of Python?

Post by Skids »

Hi,
Recently I signed up for an online course about basic Python programming as I decided that I need to have a backup plan should OpenXtalk become unavailable to me following an upgrade to MacOS.

I am wondering why anyone thought that the first item of a list or string is item with an index of zero was a good idea e.g. Name="Python", so Name[0] returns P. Python allows the count to start at the other end so you might think that the last character is at index -0 but no the last character is at index -1.

I know that this form of indexing occurs in other languages and I wonder how much time has been lost to this non intuitive indexing numbering scheme. I just know I will forget that the index starts at 0 at some point in the future.

S
Mostly using a Mac Studio M2 running MacOS Sonoma.
User avatar
tperry2x
Posts: 3208
Joined: Tue Dec 21, 2021 9:10 pm
Location: Somewhere in deepest darkest Norfolk, England
Contact:

Re: Why do indexes start at zero in the likes of Python?

Post by tperry2x »

It comes down to hangups from the past, carried over to the modern day.
When C was starting out (and assembly actually), they directly referenced the memory - no error handling, and memory registers start at 0, so indexes start at 0 too, to avoid the need for any conversion.

Looping through arrays are easier if you start at 0, otherwise if you start at 1, and your loop repeats for the number of items / lines - you have to remember to remove 1 from the end of the loop to get the right repeat count.
... and not everyone does all the time.

Python keeps 0 based indexes to stay consistent with C and assembly.

Plus, I understand why people who have a knack for maths, prefer things to start at 0. But, just don't ask me about that one.
Skids
Posts: 106
Joined: Thu Dec 22, 2022 9:40 am
Location: North Lincolnshire
Contact:

Re: Why do indexes start at zero in the likes of Python?

Post by Skids »

I guessed as much.

I've just come across the range function in python. I want the integers from 1-12 so I have to specify range(1,13). if instead I created a list then number 1 would be at list index 0 and obviously number 12 at index position 11. My favourite is that the characters in a string start at 0 but the end character is at position -1.

S
Mostly using a Mac Studio M2 running MacOS Sonoma.
Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests