Find item in list Python

In this article we will discuss different ways to check if a given element exists in list or not.

Suppose we have a list of strings i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from']
Now let’s check if given list contains a string element ‘at’ ,

Check if element exists in list using python “in” Operator

Condition to check if element is in List :

elem in LIST
It will return True, if element exists in list else return false.

For example check if ‘at’ exists in list i.e.

''' check if element exist in list using 'in' ''' if 'at' in listOfStrings : print["Yes, 'at' found in List : " , listOfStrings] Condition to check if element is not in List :

''' check if element NOT exist in list using 'in' ''' if 'time' not in listOfStrings : print["Yes, 'time' NOT found in List : " , listOfStrings]

Check if element exist in list using list.count[] function

list.count[elem]
count[element] function returns the occurrence count of given element in the list. If its greater than 0, it means given element exists in list.
''' check if element exist in list using count[] function ''' if listOfStrings.count['at'] > 0 : print["Yes, 'at' found in List : " , listOfStrings]

Check if element exist in list based on custom logic

Python any[] function checks if any Element of given Iterable is True.

Let’s use it to check if any string element in list is of length 5 i.e.

''' check if element exist in list based on custom logic Check if any string with length 5 exist in List ''' result = any[len[elem] == 5 for elem in listOfStrings] if result: print["Yes, string element with size 5 found"] Instead of condition we can use separate function in any to match the condition i.e.

def checkIfMatch[elem]: if len[elem] == 5: return True; else : return False; ''' Check if any string that satisfies the condition in checkIfMatch[] function exist in List ''' result = any[checkIfMatch for elem in listOfStrings]
Complete example is as follows,
def checkIfMatch[elem]: if len[elem] == 5: return True; else : return False; def main[]: # List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # Print the List print[listOfStrings] ''' check if element exist in list using 'in' ''' if 'at' in listOfStrings : print["Yes, 'at' found in List : " , listOfStrings] ''' check if element NOT exist in list using 'in' ''' if 'time' not in listOfStrings : print["Yes, 'time' NOT found in List : " , listOfStrings] ''' check if element exist in list using count[] function ''' if listOfStrings.count['at'] > 0 : print["Yes, 'at' found in List : " , listOfStrings] ''' check if element exist in list based on custom logic Check if any string with length 5 exist in List ''' result = any[len[elem] == 5 for elem in listOfStrings] if result: print["Yes, string element with size 5 found"] ''' Check if any string that satisfies the condition in checkIfMatch[] function exist in List ''' result = any[checkIfMatch for elem in listOfStrings] if result: print["Yes, string element with size 5 found"] if __name__ == '__main__': main[]
Output:
['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'at' found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'time' NOT found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'at' found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, string element with size 5 found Yes, string element with size 5 found
 

To find index of the first occurrence of an element in a given Python List, you can use index[] method of List class with the element passed as argument.

index = mylist.index[element]

The index[] method returns an integer that represents the index of first match of specified element in the List.

You can also provide start and end positions of the List, where the search has to happen in the list.

Following is the syntax of index[] function with start and end positions.

index = mylist.index[x, [start[,end]]]

start parameter is optional. If you provide a value for start, then end is optional.

We shall look into examples, where we go through each of these scenarios in detail.

Example 1: Find Index of item in List

In the following example, we have taken a List with numbers. Using index[] method we will find the index of item 8 in the list.

Python Program

mylist = [21, 5, 8, 52, 21, 87] item = 8 #search for the item index = mylist.index[item] print['The index of', item, 'in the list is:', index] Run

Output

The index of 8 in the list is: 2

The element is present at 3rd position, so mylist.index[] function returned 2.

Example 2: Find Index of Item in List – start, end

In the following example, we have taken a List with numbers. Using index[] method we will find the index of item 8 in the list. Also, we shall pass start and end. index[] function considers only those elements in the list starting from start index, till end position in mylist.

Python Program

mylist = [21, 8, 67, 52, 8, 21, 87] item = 8 start=2 end=7 #search for the item index = mylist.index[item, start, end] print['The index of', item, 'in the list is:', index] Run

Output

The index of 8 in the list is: 4

Explanation

mylist = [21, 8, 67, 52, 8, 21, 87] ----------------- only this part of the list is considered ^ index finds the element here 0 1 2 3 4 => 4 is returned by index[]

Example 3: Find Index of Item – Item has multiple occurrences in List

A Python List can contain multiple occurrences of an element. In such cases, only the index of first occurrence of specified element in the list is returned.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 52 #search for the item index = mylist.index[item] print['The index of', item, 'in the list is:', index] Run

Output

The index of 52 in the list is: 3

The element 52 is present two times, but only the index of first occurrence is returned by index[] method.

Let us understand how index[] method works. The function scans the list from starting. When the item matches the argument, the function returns that index. The later occurrences are ignored.

Example 4: Find Index of Item in List – Item not present

If the element that we are searching in the List is not present, you will get a ValueError with the message item is not in list.

In the following program, we have taken a list and shall try to find the index of an element that is not present in the list.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 67 #search for the item/element index = mylist.index[item] print['The index of', item, 'in the list is:', index] Run

Output

Traceback [most recent call last]: File "example.py", line 5, in index = mylist.index[item] ValueError: 67 is not in list

As index[] can throw ValueError, use Python Try-Except while using index[]. In the following example, we shall learn how to use try-except statement to handle this ValueError.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 67 try: #search for the item index = mylist.index[item] print['The index of', item, 'in the list is:', index] except ValueError: print['item not present'] Run

Output

item not present

The item, whose index we are trying to find, is not present in the list. Therefore, mylist.index[item] throws ValueError. except ValueError: block catches this Error and the corresponding block is executed.

Summary

In this Python Tutorial, we learned how to find the index of an element/item in a list, with the help of well detailed examples.

Python has different data types to store the collection of data. Python list is one of them and a list can contain different types of data like number, string, boolean, etc. Sometimes, it requires to search particular elements in a list. The elements can be searched in the python list in various ways. How you can find any element and a list of elements in the list are explained in this tutorial using various examples.

Example-1: Find a single element in a list using ‘in’ operator

The following script shows how you can easily search any element in a list by using ‘in’ operator without using any loop. A list of flower names is defined in the script and a flower name will be taken as input from the user to search in the list. If statement is used with ‘in’ operator to find the input flower name in the list.

#!/usr/bin/env python3
# Define a list of flowers
flowerList = ['rose', 'daffodil', 'sunflower', 'poppy', 'bluebell']

# Take the name of the flower that you want to search in the list


flowerName = input["Enter a flower name:"]

# Search the element using 'in' operator


if flowerName.lower[] in flowerList:

  # Print success message


  print["%s is found in the list" %[flowerName]]
else:

  # Print not found message


  print["%s is not found in the list" %[flowerName]]

Output:

The output shows Daffodil exists in the list and Lily does not exist in the list.

Example-2: Find an element by using the index method

Another simple way to find a particular element in a list using the index method. The following script shows the use of index[] method for searching an element in a list. This method returns a valid index position if the particular element is found in the list otherwise it will generate a ValueError if you want to store the position in a variable. the try block will print the success message if the index[] method returns a valid position value based on search value. The except block will print the failure message if the searching element does not exist in the list.

#!/usr/bin/env python3
try:
  # Define a list of books
  bookList = ['The Cat in the Hat', 'Harold and the Purple Crayon',
    'The Very Hungry Caterpillar', 'Goodnight Moon', 'Harold and the Purple Crayon']

  # Take the name of the book that you want to search in the list


  bookName = input["Enter a book name:"]
  # Search the element using index method
  search_pos = int[bookList.index[bookName]]

  # Print found message


  print["%s book is found in the list" %[bookName]]
except[ValueError]:
  # Print not found message
  print["%s book is not found in the list" %[bookName]]

Output:

The output shows ‘Goodnight Moon’ exists in the list and ‘Charlie and the Chocolate Factory’ does not exist in the list.

Example-3: Find multiple indices in a list

How you can find a single element in a list is shown in the previous two examples. The following script shows how you can search all elements of a list inside another list. Three lists are used in this script. selectedList is the main list in which the elements of searchList will be searched. foundList is used here to store those elements that are found in selectedList after searching. The first for loop is used to generate foundList and the second for loop is used to iterate foundList and display the output.

#!/usr/bin/env python3
# Define a list of selected persons
selectedList = ['Sophia', 'Isabella', 'Olivia', 'Alexzendra', 'Bella']
# Define a list of searching person
searchList = ['Olivia', 'Chloe','Alexzendra']
# Define an empty list
foundList = []

# Iterate each element from the selected list


for index, sList in enumerate[selectedList]:
  # Match the element with the element of searchList
  if sList in searchList:
    # Store the value in foundList if the match is found
    foundList.append[selectedList[index]]

# iterate the searchList


for val in searchList:
  # Check the value exists in foundList or not
  if val in foundList:
    print["%s is selected.\n" %val]
  else:
    print["%s is not selected.\n" %val]

Output:

The following output will appear after running the word.

Example-4: Find an element using the custom function

If you want to find the element multiple times in a list then it is better to use a custom search method instead of writing a search script multiple times. The following script shows how you can find any value in a list using a custom function named findElement. The function will return True if the list contains the search element otherwise returns False.

#!/usr/bin/env python3
# Define a list of food
food = ['pizza', 'cake', 'strawberry', 'chocolate','chicken fry','mango']
# Take a food name from the user
search = input['Type your favorite food : ']

# Define the custom function to find element in the list


def findElement[listName, searchElement]:
  # Read the list using loop
  for value in listName:
  # Check the element value is equal to the search value or not
    if value == searchElement:
      return True

    # Return false if no match found


    return False

# Call the function with the list name and search value


if findElement[food, search.lower[]]:
  print["%s is found" %search]
else:
  print["%s is not found" %search]

Output:

The following output will appear for the input ‘Cake’ and ‘Chocolate Cake’.

Example-5: Find and count the elements in a list based on length

The following script shows how you can find and count the number of elements in a list based on the element’s length. Here, the list named persons is iterate using for loop and check the length of each element of the list. The counter value increments if the length of the element is more than or equal to 7.

#!/usr/bin/env python3
# Define a list of persons
persons = ['Sophia', 'Isabella', 'Olivia', 'Alexzendra', 'Bella']

# Initialize thecounter


counter = 0
# Iterate the list using loop
for name in persons:
  # Check the length of the element
  if [len[name] >= 7] :
    # Increment counter by one
    counter = counter + 1

# Check the counter value


if [counter > 0]:
  print["%d person[s] name length is/are more than 7." %counter]
else:
  print["The name length of all persons are less than 7."]

Output:

The following output will appear after running the script.

Conclusion:

Different ways of searching single and multiple elements in the list are shown in this tutorial using in operator, index method, and custom function. The reader will be able to perform searching properly in the python list after reading this tutorial.

Watch Author’s Video: here

Video liên quan

Chủ Đề