List items are indexed in Python and we can use index
number to access them. Index starts from 0 and ends at length of the list -1
Print the second item of the list:
print(mylist[1])
Negative Indexing in Python is allowed and negative
indexing means start from the end
Print the last item of the list:
print(mylist[-1])
Range of indexes can be specified to access number of elements at a time. When specifying a range, the return value will be a new list with the specified items.
Return the third, fourth, and fifth item:
print(mylist[startindex:endindex])
The search will start at index 'startindex' and end at
'endindex-1'. If the statement is print(mylist[2:5]), it will fetch values at
index 2,3 and 4 and the output would be ['Chennai', 'Delhi', 'Goa']
If the 'startindex' is kept vacant, it will become 0
print(mylist[:4])
It will fetch values from index 0 to index 3
If the 'endindex' is kept vacant, it will fetch values
from specified 1st index to last index of the list.
Example
This example returns the items from "cherry"
to the end:
print(mylist[2:])
No comments:
Post a Comment