Python search value in list

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

You can use the “in operator” to check if an element is in the list. The “ in” operator allows you to check if an element exists in the list. If you need the index of the element or need to perform a more advanced search, you can use the “enumerate()” function combined with a for loop or a list comprehension.

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 2: Using enumerate() with for loop

main_list = [11, 21, 19, 18, 46] search_element = 19 found_element = False for index, item in enumerate(main_list): if item == search_element: found_element = True print(f" found_element at index ") break if not found_element: print(f" not found_element in the list")
19 found_element at index 2

Method 3: Using list comprehension to get indices

main_list = [11, 21, 19, 18, 46] search_element = 19 indices = [index for index, item in enumerate( main_list) if item == search_element] if indices: print(f" found at indices ") else: print(f" not found in the list")

Method 4: 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.

Читайте также:  Php ini in xampp windows

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 5: 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 6: 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 7: Using the filter() method

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

Читайте также:  Javascript and css loader

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 8: 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.

Источник

5 способов поиска элемента в списке Python

5 способов поиска элемента в списке Python

Статьи

Введение

В ходе статьи рассмотрим 5 способов поиска элемента в списке Python.

Поиск методом count

Метод count() возвращает вхождение указанного элемента в последовательность. Создадим список разных цветов, чтобы в нём производить поиск:

colors = ['black', 'yellow', 'grey', 'brown']

Зададим условие, что если в списке colors присутствует элемент ‘yellow’, то в консоль будет выведено сообщение, что элемент присутствует. Если же условие не сработало, то сработает else, и будет выведена надпись, что элемента отсутствует в списке:

colors = ['black', 'yellow', 'grey', 'brown'] if colors.count('yellow'): print('Элемент присутствует в списке!') else: print('Элемент отсутствует в списке!') # Вывод: Элемент присутствует в списке!

Поиск при помощи цикла for

Создадим цикл, в котором будем перебирать элементы из списка colors. Внутри цикла зададим условие, что если во время итерации color приняла значение ‘yellow’, то элемент присутствует:

colors = ['black', 'yellow', 'grey', 'brown'] for color in colors: if color == 'yellow': print('Элемент присутствует в списке!') # Вывод: Элемент присутствует в списке!

Поиск с использованием оператора in

Оператор in предназначен для проверки наличия элемента в последовательности, и возвращает либо True, либо False.

Зададим условие, в котором если ‘yellow’ присутствует в списке, то выводится соответствующее сообщение:

colors = ['black', 'yellow', 'grey', 'brown'] if 'yellow' in colors: print('Элемент присутствует в списке!') else: print('Элемент отсутствует в списке!') # Вывод: Элемент присутствует в списке!

В одну строку

Также можно найти элемент в списке при помощи оператора in всего в одну строку:

colors = ['black', 'yellow', 'grey', 'brown'] print('Элемент присутствует в списке!') if 'yellow' in colors else print('Элемент отсутствует в списке!') # Вывод: Элемент присутствует в списке!
colors = ['black', 'yellow', 'grey', 'brown'] if 'yellow' in colors: print('Элемент присутствует в списке!') # Вывод: Элемент присутствует в списке!

Поиск с помощью лямбда функции

В переменную filtering будет сохранён итоговый результат. Обернём результат в список (list()), т.к. метода filter() возвращает объект filter. Отфильтруем все элементы списка, и оставим только искомый, если он конечно присутствует:

colors = ['black', 'yellow', 'grey', 'brown'] filtering = list(filter(lambda x: 'yellow' in x, colors))

Итак, если искомый элемент находился в списке, то он сохранился в переменную filtering. Создадим условие, что если переменная filtering не пустая, то выведем сообщение о присутствии элемента в списке. Иначе – отсутствии:

colors = ['black', 'yellow', 'grey', 'brown'] filtering = list(filter(lambda x: 'yellow' in x, colors)) if filtering: print('Элемент присутствует в списке!') else: print('Элемент отсутствует в списке!') # Вывод: Элемент присутствует в списке!

Поиск с помощью функции any()

Функция any принимает в качестве аргумента итерабельный объект, и возвращает True, если хотя бы один элемент равен True, иначе будет возвращено False.

Читайте также:  Php создание файла json

Создадим условие, что если функция any() вернёт True, то элемент присутствует:

colors = ['black', 'yellow', 'grey', 'brown'] if any(color in 'yellow' for color in colors): print('Элемент присутствует в списке!') else: print('Элемент отсутствует в списке!') # Вывод: Элемент присутствует в списке!

Внутри функции any() при помощи цикла производится проверка присутствия элемента в списке.

Заключение

В ходе статьи мы с Вами разобрали целых 5 способов поиска элемента в списке Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

Источник

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