In this post, we will learn about how to index lists in Python.

The index() method returns the index of an item in Python list.

Python Index List Format

list.index(element, start, end)

list index() parameters...

The list index() method can take a maximum of three arguments:

  • element - the element to be searched
  • start (optional) - start searching from this index
  • end (optional) - search the element up to this index

Python Get Index Of Item In List

Example: Get the index of 2nd item in the following list...

mylist = ['CA', 'MA', 'OR', 'AZ','NV']

To get the 2nd element which is 'MA' in our list,  do following...

index = mylist.index('MA')
print('Index of MA is',index)

The output of above command...

Index of MA is 1

Python Not In List Error

Let us try to access an element which is not in the list

mylist = ['CA', 'MA', 'OR', 'AZ','NV']
index = mylist.index('KY')

You will get following error...

ValueError: 'KY' is not in list

To avoid the above error, always check if in list...

If In List Python

Example: find element in list Python. Let us check if 'KY' in mylist.

mylist = ['CA', 'MA', 'OR', 'AZ','NV']
if 'KY' in mylist:
	print('KY is in list')
	print('KY is not in list')

Output of above code...

KY is not in list

Python Get Item From List By Index

Example: Get 2nd item from following list. Note in Python index starts from 0.

 mylist = ['CA', 'MA', 'OR', 'AZ','NV']

Output of above command...


List Index Out Of Range

If we try to use an index which is in the list, Python will throw an error.


 mylist = ['CA', 'MA', 'OR', 'AZ','NV']

Output of above command...

IndexError: list index out of range

Also checkout how to remove element from Python list.