
Zero-based indexing
Data stored in ordered arrays like lists and tuples often needs to be individually accessed. To directly access a particular item within a list or tuple, you need to pass its index number to the array in square brackets. This makes it important to remember that Python indexing and counting starts at 0 instead of 1. This means that the first member of a group of data is at the 0 index position, and the second member is at the 1 index position, and so on:
>>> newlist = ['run','chase','dog','bark']
>>> newlist[0]
'run'
>>> newlist[2]
'dog'
Zero-based indexing applies to characters within a string. Here, the list item is accessed using indexing, and then individual characters within the string are accessed, also using indexing:
>>> newlist[3][0]
'b'
Zero-based indexing also applies when there is a for loop iteration within a script. When the iteration starts, the first member of the data container being iterated is data item 0, the next is data item 1, and so on:
>>> newlist = ['run','chase','dog','bark']
>>> for counter, item in enumerate(newlist):
print counter, newlist[counter]
0 run
1 chase
2 dog
3 bark