All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Search Element In List Python

Last Updated : Mar 11, 2024

Search Element In List Python

In this article we will show you the solution of search element in list python, a popular operation in Python that enables you to determine the existence or location of a particular value inside a group of objects is searching for an element in a list.

One of the fundamental Python data structures, lists offer an organized succession of elements that are easily accessed and changed.

Iteratively going over each item in the list and comparing it to the desired value is how you find an element in a list.

Python provides some methods to complete this task. One simple method is to iterate over the list using a for loop, checking each entry against the required value.

As an alternative, you can use built-in functions to retrieve the index or ascertain whether the element is present in the list, such as index() or the in operator.

We'll talk about the list Python concept of the search element.

Step By Step Guide On Search Element In List Python :-

def linear_search(list, target):
    """Performs a linear search to find the target element in the list."""
    for i in range(len(list)):
        if list[i] == target:
            return i # Returns the index of the target element if found
    return -1 # Returns -1 if the target element is not found
def binary_search(list, target):
    """Performs a binary search to find the target element in a sorted list."""
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = (low + high) // 2
        if list[mid] == target:
            return mid # Returns the index of the target element if found
        elif list[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1 # Returns -1 if the target element is not found
def main():
    numbers = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
    target = 16
    linear_result = linear_search(numbers, target)
    if linear_result != -1:
        print(f"The target element {target} is found at index {linear_result} using linear search.")
    else:
        print("The target element is not found using linear search.")
    numbers.sort()
    binary_result = binary_search(numbers, target)
    if binary_result != -1:
        print(f"The target element {target} is found at index {binary_result} using binary search.")
    else:
        print("The target element is not found using binary search.")
if __name__ == "__main__":
    main()
  1. The linear_search function, which accepts a list and a target element as input, is used at the beginning of the code.
  2. Using a for loop to iterate through the list, we conduct a linear search.
  3. Every element in the list is compared to the target element.
  4. If a match is made, the target element's index is returned.
  5. We return -1 to show that the target element is not present in the list if the loop ends without producing a match.
  6. A sorted list & a target element are required arguments for the binary_search function.
  7. The lower and upper limits of the search range are represented by the pointers low and high, which we initialize first.
  8. The while loop then begins and runs until the low pointer equals the high pointer or falls below it.
  9. We determine the middle index as (low + high) // 2 for each iteration and contrast the element at that position with the target element.
  10. We return the index if they match. In order to search in the upper half of the list, we update the low pointer to low + 1 if the middle element is less than the target.
  11. The high pointer is changed to mid - 1 to search in the lower half if the middle element is bigger than the target.
  12. The cycle repeats until either the boundaries converge or the target element is located.
  13. We return -1 if the desired element cannot be found.
  14. For testing purposes, we generate a sample list called numbers in the main function. 16 has been set as the target element.
  15. First, we use the linear_search function to do a linear search, recording the results in the linear_result variable.
  16. If linear_result does not equal 1, we output a message stating that linear search has successfully located the target element at the specified index.
  17. If the target element cannot be found, we print a message stating as much.
  18. We then carry out a binary search. We sort the numbers list using the sort function because it needs a sorted list.
  19. The binary search is then carried out, and the outcome is saved in binary_result, using the binary_search function.
  20. We verify that binary_result is not -1 and print a message in response, just like the linear search.

Conclusion :-

As a result, we were able to understand the concept of a search element in list Python.

Additionally, we discovered that in Python, looking for a certain element in a list is a typical operation.

It entails going over the list repeatedly and contrasting each item with the desired value.

I hope this article on search element in list python helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Anjali

Experienced Computer Programmer with a broad range of experience in technology. Strengths in application development and Object Oriented architecture design, front end programming, usability and multimedia technology. Expert in coding languages such as C, C++ Java, JavaScript, PHP and more.

Follow Anjali On Linkedin 🡪