A list is an important container in Python, as if it stores items of all data types as a collection. Knowledge of certain list operations is essential for daytime programming. This article discusses one of the basic list operations, which allows you to check if an item is in the list.
Method 1: Naive method
In the “ Naive ”it is easy to use a loop that iterates over all the elements to check for the existence of the target element. This is the easiest way to check if an item is in the list.
Method 2: Using
in — this is the most common way to check if an item exists in the list or not. This particular way returns True if the item exists in the list and False if the item does not exist in the list. The list does not need to be sorted to practice this validation approach.
Code # 1: Demo to check if an item is in a list using Naive method and
Checking if 4 exists in list (using loop): Element Exists Checking if 4 exists in list (using in): Element Exists
Method 3: Using
set () +
Converting a list to a set and then using in may be more efficient than using
in . But having efficiency for plus also has certain disadvantages. One is that the order of the list is not preserved, and if you decide to take a new list for it, you will need to use the extra space. Another disadvantage is that the set disallows duplication, and therefore duplicate elements will be removed from the original list.
The usual binary search way to check for the existence of an element, so the list must be sorted first and hence , do not preserve the order of the elements.
lower_bound () in C ++ STL.
Code # 2: Demo for checking if an item exists in a list using
set () +
sort () +
bisect_left () .