Tuesday, January 5, 2021

How To Access List Items In Python

 

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

 Example

Print the second item of the list:

 mylist = ["Assam", "Banaras", "Chennai"]

print(mylist[1])

 Output: Banaras

 

Negative Indexing in Python is allowed and negative indexing means start from the end

 -1 refers to the last item, -2 refers to the second last item and so on

 Example

Print the last item of the list:

 mylist = ["Assam", "Banaras", "Chennai"]

print(mylist[-1])

 Output: Chennai

 

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.

 Example

Return the third, fourth, and fifth item:

 mylist = ["Assam", "Banaras", "Chennai", "Delhi", "Goa", "Indore"]

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

 mylist = ["Assam", "Banaras", "Chennai", "Delhi", "Goa", "Indore"]

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:

 mylist = ["Assam", "Banaras", "Chennai", "Delhi", "Goa", "Indore"]

print(mylist[2:])

 It will display ['Chennai', 'Delhi', 'Goa', 'Indore']


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner