Python find in list | list index python

In this post, we will see how to find the index of an item in the List, but first, we will sneak into the basics of Python Lists.

What are Python Lists?

Lists are one of the simple and most commonly used data structures in python which can store multiple data types at the same time like string, int, boolean, etc, and hence it is called heterogeneous.

Lists are mutable, which means the data inside the list can be altered or changed. Lists contain ordered data and can also contain duplicate values.

A List looks like this: [‘Tom’, 35, ‘New York’, 044, TRUE] Here we have a list that contains three types of data, string, integer, and boolean. List stores each data at a particular index which starts from 0. Here Tom is stored at index 0, 35 is stored at index 1, and so on.

Creating a list and printing all its content

mylist = ['Brad', 'Sam', 23, 'Chan']
print(mylist)
Output: [‘Brad’, ‘Sam’, 23, ‘Chan’]

Getting the length of a list

mylist = ['Brad', 'Sam', 23, 'Chan']
print(len(mylist))
Output: 4

Getting a particular item of a list

Since a list stores each data at a particular index, we can access that data using the index. See example below:

mylist = ['Brad', 'Sam', 23, 'Chan']
print(mylist(1))
print(mylist(2))
Output: Sam
23

You can read more about Python List here.

Finding a particular item in the list using index (Python find in list)

As we have seen above that a list stores data with index notation, we can find a particular item in the list using the index() function. The result will return the index of that data if it’s present there or simply throw ValueError if it’s not present there.

Let’s understand by an example:

list = ['abc', 'def', 'ghi', 'jkl', 'mno']
#We will find whether 'ghi' is in the list or not
print(list.index('ghi'))
Output: 2
list = ['abc', 'def', 'ghi', 'jkl', 'mno']
#We will find whether 'pqr' is in the list or not
print(list.index('pqr'))
Output: ValueError: ‘pqr’ is not in list

The index() method returns the position at the first occurrence of the specified value. If there are duplicate values in the list, index() method will show the index of the first occurrence of that element. Let’s see:

numbers = [4, 55, 64, 32, 16, 32]
#This is a list of numbers with 32 occuring two times
#The index() method will show the index of the first occurence of 32

print(numbers.index(32))
Output: 3

More to read: