find item in list

How to Find Element in List in Python

Sometimes you may need to search for an item in Python list, or search if an item exists in a list, or search for a string in list. There are multiple ways to do this easily using Python. In this article, we will look at the different ways to find element in list in Python.


How to Find Element in List in Python

Here are the different ways to find element in List in Python.


1. Using Index

You can easily find an element in Python list using index() function. It returns the index of an element in the list. Here is an example.

>>> a=['Sunday','Monday','Tuesday']
>>> pos=a.index('Monday')
>>> pos
1

Please note, the index of first element in a list is 0. Index() function takes a single argument which is the item whose index you want to find. The above example works with both numerical and string items.


2. Check if item exists in List

Sometimes you may need to find if an item exists in a list. You can easily do this using ‘in’ operator. There is no need to loop through the list to check if an item exists or not. Here is an example to check if ‘Monday’ is present in the list.

>>> a=['Sunday','Monday','Tuesday']
>>> 'Monday' in a
True


3. Find Multiple items in List

Sometimes you may have indices of multiple items. Here is a simple way to extract those items from the list, using list comprehensions.

>>> a=['Sunday','Monday','Tuesday']
>>> b=[0,2]
>>> [a[i] for i in b]
['Sunday', 'Tuesday']

In this article, we have looked at two different ways to find element in Python list. We have also looked at how to extract multiple items from list using their indices. These are very useful operations often required in Python applications.

Also read:

How to Parse CSV in Shell
Find All Symlinks to File/Folder in Linux
Shell Script to Count Number of Files in Directory
Shell Script to Count Number of Words in File
How to Enable & Disable Services in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *