You will:
Methods of searching elements in list;
Do you have any method to find anything fast?
Проверка наличия элемента в списке
Список является важным контейнером в Python, поскольку он хранит элементы всех типов данных в виде коллекции. Сейчас вы познакомитесь с одной из основных операций со списком способов проверить наличие элемента в списке.
Method #1: использование цикла
Этот метод использует цикл, который перебирает все элементы для проверки существования целевого элемента. Это самый простой способ проверить наличие элемента в списке.
Example 1
# Initializing list
my_list = [ 1, 6, 3, 5, 3, 4 ]
print(“Checking if 4 exists in list (using loop):“)
for i in my_list:
if(i == 4) :
print (“Element Exists”)
Output
Checking if 4 exists in list (using loop):
Element Exists
Method #2: using “in”
Python in is the most conventional way to check if an element exists in list or not. This particular way returns True if element exists in list and False if the element does not exist in the list. The list need not be sorted to practice this approach of checking.
Example 2
# Checking if 4 exists in list using in
if (4 in my_list):
print (“Element Exists”)
Output
Checking if 4 exists in list (using in):
Element Exists
Method #3: using set() + in
Converting the list into set and then using “in” can possibly be more efficient than only using “in”. But having efficiency for a plus also has certain negatives. One among them is that the order of list is not preserved, and if you opt to take a new list for it, you would require to use extra space. Another drawback is that set disallows duplication and hence duplicate elements would be removed from the original list.
Example 3
# Initializing list
list_set = [ 1, 6, 3, 5, 3, 4 ]
print(“Checking if 4 exists in list (using set()+in):“)
list_set = set(list_set)
if 4 in list_set :
print (“Element Exists”)
Output
Checking if 4 exists in list (using set()+in):
Element Exists
Practice 1
1. Create and initialize a list;
2. Enter random 10 numbers into the list;
3. Input any number you like;
4. The program should check the number you like exists in the list;
5. Use different methods.
Practice 2
1. Create two lists;
2. Add 5 elements to the first list using append() method;
3. Add 5 elements to the second list using extend() method;
4. The program should check the number you like exists in the list;
5. Check all items and print out elements that exist in both lists.
Hint: use for loop and in method.