Python list of list find element

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

About the author

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

How do I find a specific element in a list Python?

To find an element in the list, use the Python list index[] method, The index[] is an inbuilt Python method that searches for an item in the list and returns its index. The index[] method finds the given element in the list and returns its position.

How do you find if an element is present in a list?

We can use the in-built python List method, count[], to check if the passed element exists in the List. If the passed element exists in the List, the count[] method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

How do you find the index of a list in a list Python?

Find the Index of an Item using the List index[] Method in Python.
my_list is the name of the list you are searching through..
. index[] is the search method which takes three parameters. ... .
item is the required parameter. ... .
start is the first optional parameter. ... .
end the second optional parameter..

Bài mới nhất

Chủ Đề