Check if an element is present in the list
We will take a list as input from the user and then ask the user to enter the element's value to be searched. Then we will return YES/NO based on whether the element is present in the list or not.
Example:
Input:
[4, 2, 9, 5, 1, 0, 7] element -> 5
Output:
Present
Python provides us multiple ways to perform the tasks. And to check for an element's presence also, we can use multiple ways in which the present can be check.
Method 1: Searching technique
To check whether an element is present in a list or not. We can simply use any searching technique and find the element in the list.
Here, we will discept linear search.
Program to check if an element is present in the list
Output:
Method 2: Using in operator
Python programming language provides us an operator "in" to check whether an element is present in a list.
Syntax:
Returns boolean values based on the presence of element in the list.
Algorithm:
Program to check if an element is present in a list using in operator
Output:
Method 3: Using bisect_left() method on sorted list
The list needs to be sorted in order to apply this method.
The bisect_left() method find's and returns the first occurrence of the given element in a sorted array.
Syntax:
Returns a boolean value based on whether the element is present in the list or not.
Program to check if an element is present in list
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer