Find function in python list

Python Find in List: How to Find an Element in List

Method 1: Using the “index()” method

To find an element in the Python list, you can use the list index() method. The list index() is a built-in method that searches for an element in the list and returns its index.

If the same element is present more than once, the method returns the index of the first occurrence of the element. The index in Python starts from 0, not 1. So, through an index, we can find the position of an element in the list.

Example

streaming = ['netflix', 'hulu', 'disney+', 'appletv+'] index = streaming.index('disney+') print('The index of disney+ is:', index)

The list.index() method takes a single argument, the element, and returns its position in the list.

Method 2: Using “in operator”

Use the “in operator” to check if an element is in the list.

Читайте также:  Dao patterns in java

Example

main_list = [11, 21, 19, 46] if 19 in main_list: print("Element is in the list") else: print("Element is not in the list")

You can see that the element “19” is in the list. That’s why “in operator” returns True.

If you check for the element “50,” then the “in operator” returns False and executes the else statement.

Method 3: Using the count() function

The list.count() method returns the number of times the given element in the list.

Syntax

The count() method takes a single argument element, the item that will be counted.

Example

main_list = [11, 21, 19, 46] count = main_list.count(21) if count > 0: print("Element is in the list") else: print("Element is not in the list")

We count the element “21” using the list in this example.count() function, and if it is greater than 0, it means the element exists; otherwise, it is not.

Method 4: Using list comprehension with any()

The any() is a built-in Python function that returns True if any item in an iterable is True. Otherwise, it returns False.

Example

main_list = [11, 21, 19, 46] output = any(item in main_list for item in main_list if item == 22) print(str(bool(output)))

You can see that the list does not contain “22”. So, finding “22” in the list will return False by any() function.

If any() function returns True, an element exists in the list; otherwise, it does not.

Method 5: Using the filter() method

The filter() method iterates through the list’s elements, applying the function to each.

The filter() function returns an iterator that iterates through the elements when the function returns True.

Example

main_list = [11, 21, 19, 46] filtered = filter(lambda element: element == 19, main_list) print(list(filtered))

Method 6: Using the for loop

You can find if an element is in the list using the for loop in Python.

Example

main_list = [11, 21, 19, 46] for i in main_list: if(i == 46): print("Element Exists")

In this example, we traversed a list element by element using the for loop, and if the list’s element is the same as the input element, it will print “Element exists”; otherwise not.

Источник

How to find the element in python list

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 ) )

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 ) )

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 )

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 )

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.» )

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.

About the author

Fahmida Yesmin

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.

Источник

Оцените статью