Как найти элемент в массиве python функция

What is a good way to find the index of an element in a list in Python?
Note that the list may not be sorted.

Is there a way to specify what comparison operator to use?

Benyamin Jafari's user avatar

asked Mar 3, 2009 at 1:45

Himadri Choudhury's user avatar

2

From Dive Into Python:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5

stivlo's user avatar

stivlo

83.2k31 gold badges142 silver badges199 bronze badges

answered Mar 3, 2009 at 1:52

Matt Howell's user avatar

3

If you just want to find out if an element is contained in the list or not:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
True
>>> 'damn' in li
False

answered Feb 17, 2011 at 10:00

Eduardo's user avatar

EduardoEduardo

1,7811 gold badge11 silver badges5 bronze badges

0

The best way is probably to use the list method .index.

For the objects in the list, you can do something like:

def __eq__(self, other):
    return self.Value == other.Value

with any special processing you need.

You can also use a for/in statement with enumerate(arr)

Example of finding the index of an item that has value > 100.

for index, item in enumerate(arr):
    if item > 100:
        return index, item

Source

tedder42's user avatar

tedder42

23.2k12 gold badges86 silver badges100 bronze badges

answered Mar 3, 2009 at 1:51

Brian R. Bondy's user avatar

Brian R. BondyBrian R. Bondy

338k124 gold badges592 silver badges635 bronze badges

Here is another way using list comprehension (some people might find it debatable). It is very approachable for simple tests, e.g. comparisons on object attributes (which I need a lot):

el = [x for x in mylist if x.attr == "foo"][0]

Of course this assumes the existence (and, actually, uniqueness) of a suitable element in the list.

answered Sep 24, 2010 at 9:35

ThomasH's user avatar

ThomasHThomasH

22.1k13 gold badges60 silver badges61 bronze badges

3

assuming you want to find a value in a numpy array,
I guess something like this might work:

Numpy.where(arr=="value")[0]

Jorgesys's user avatar

Jorgesys

124k23 gold badges329 silver badges265 bronze badges

answered Jan 27, 2011 at 15:03

Sebastian Gurovich's user avatar

2

There is the index method, i = array.index(value), but I don’t think you can specify a custom comparison operator. It wouldn’t be hard to write your own function to do so, though:

def custom_index(array, compare_function):
    for i, v in enumerate(array):
        if compare_function(v):
            return i

answered Mar 3, 2009 at 1:50

David Z's user avatar

David ZDavid Z

127k27 gold badges252 silver badges277 bronze badges

I use function for returning index for the matching element (Python 2.6):

def index(l, f):
     return next((i for i in xrange(len(l)) if f(l[i])), None)

Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.

element = mylist[index(mylist, lambda item: item["name"] == "my name")]

If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:

def find_name(l, name):
     return l[index(l, lambda item: item["name"] == name)]

And then it is quite easy and readable:

element = find_name(mylist,"my name")

answered Oct 20, 2011 at 12:30

jki's user avatar

jkijki

4,6171 gold badge34 silver badges29 bronze badges

0

The index method of a list will do this for you. If you want to guarantee order, sort the list first using sorted(). Sorted accepts a cmp or key parameter to dictate how the sorting will happen:

a = [5, 4, 3]
print sorted(a).index(5)

Or:

a = ['one', 'aardvark', 'a']
print sorted(a, key=len).index('a')

answered Mar 3, 2009 at 1:52

Jarret Hardie's user avatar

Jarret HardieJarret Hardie

94.4k10 gold badges132 silver badges126 bronze badges

how’s this one?

def global_index(lst, test):
    return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )

Usage:

>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]

answered Mar 3, 2009 at 2:06

SingleNegationElimination's user avatar

2

I found this by adapting some tutos. Thanks to google, and to all of you ;)

def findall(L, test):
    i=0
    indices = []
    while(True):
        try:
            # next value in list passing the test
            nextvalue = filter(test, L[i:])[0]

            # add index of this value in the index list,
            # by searching the value in L[i:] 
            indices.append(L.index(nextvalue, i))

            # iterate i, that is the next index from where to search
            i=indices[-1]+1
        #when there is no further "good value", filter returns [],
        # hence there is an out of range exeption
        except IndexError:
            return indices

A very simple use:

a = [0,0,2,1]
ind = findall(a, lambda x:x>0))

[2, 3]

P.S. scuse my english

answered Oct 16, 2011 at 11:41

Gael's user avatar

На чтение 4 мин Просмотров 5.5к. Опубликовано 03.03.2023

Содержание

  1. Введение
  2. Поиск методом count
  3. Поиск при помощи цикла for
  4. Поиск с использованием оператора in
  5. В одну строку
  6. Поиск с помощью лямбда функции
  7. Поиск с помощью функции any()
  8. Заключение

Введение

В ходе статьи рассмотрим 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.

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

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

if any(color in 'yellow' for color in colors):
    print('Элемент присутствует в списке!')
else:
    print('Элемент отсутствует в списке!')

# Вывод: Элемент присутствует в списке!

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

Заключение

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

The list is an important container in python as it stores elements of all the data types as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses the Fastest way to check if a value exists in a list or not using Python.

Example:

list = test_list = [1, 6, 3, 5, 3, 4]
Input: 3  # Check if 3 exist or not.
Output: True
Input: 7  # Check if 7 exist or not.
Output: False

Method 1: Naive Method

In the Naive method, one easily uses a loop that iterates through all the elements to check the existence of the target element. This is the simplest way to check the existence of the element in the list. Python is the most conventional way to check if an element exists in a list or not. This particular way returns True if an element exists in the 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 1: Check if an element exists in the list using the if-else statement

Python3

lst=[ 1, 6, 3, 5, 3, 4 ]

i=7

if i in lst:

    print("exist")

else:

    print("not exist")

Time Complexity: O(1)
Auxiliary Space: O(n), where n is total number of elements.

Example 2: Check if an element exists in the list using a loop 

Python3

test_list = [1, 6, 3, 5, 3, 4]

for i in test_list:

    if(i == 4):

        print("Element Exists")

Output:

Element Exists

Time Complexity: O(n)
Auxiliary Space: O(1)

Example 3: Check if an element exists in the list using “in” 

Python3

test_list = [1, 6, 3, 5, 3, 4]

if (4 in test_list):

    print("Element Exists")

Output:

Element Exists

Example 4: Check if an element exists in the list using any() function

Python3

test_list = [1, 6, 3, 5, 3, 4]

result = any(item in test_list for item in test_list)

print("Does string contain any list element : " +str(bool(result)))

Output:

Does string contain any list element : True

Method 2: Check if an element exists in the list using count()

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List. Demonstrating to check the existence of elements in the list using count().

Python3

test_list = [10, 15, 20, 7, 46, 2808]

print("Checking if 15 exists in list")

exist_count = test_list.count(15)

if exist_count > 0:

    print("Yes, 15 exists in list")

else:

    print("No, 15 does not exists in list")

Output:

Checking if 15 exists in list
Yes, 15 exists in list

Method 3: Check if an element exists in the list using sort + bisect_left + set

Converting the list into the set and then using it can possibly be more efficient than only using it. But having efficiency for a plus also has certain negatives. One among them is that the order of the 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 duplicity and hence duplicate elements would be removed from the original list. In the conventional binary search way of testing element existence, hence list has to be sorted first and hence does not preserve the element ordering. bisect_left() returns the first occurrence of the element to be found and has worked similarly to lower_bound() in C++ STL.

Note: The bisect function will only state the position of where to insert the element but not the details about if the element is present or not.

Demonstrating to check existence of element in list using set() + in and sort() + bisect_left()

Python3

from bisect import bisect_left ,bisect

test_list_set = [ 1, 6, 3, 5, 3, 4 ]

test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]

print("Checking if 4 exists in list ( using set() + in) : ")

test_list_set = set(test_list_set)

if 4 in test_list_set :

    print ("Element Exists")

print("Checking if 4 exists in list ( using sort() + bisect_left() ) : ")

test_list_bisect.sort()

if bisect_left(test_list_bisect, 4)!=bisect(test_list_bisect, 4):

    print ("Element Exists")

else:

    print("Element doesnt exist")

Output:

Checking if 4 exists in list ( using set() + in) : 
Element Exists
Checking if 4 exists in list ( using sort() + bisect_left() ) : 
Element Exists

Method 4: Using find() method

Python3

test_list = [10, 15, 20, 7, 46, 2808]

print("Checking if 15 exists in list")

x=list(map(str,test_list))

y="-".join(x)

if y.find("15") !=-1:

    print("Yes, 15 exists in list")

else:

    print("No, 15 does not exists in list")

Output

Checking if 15 exists in list
Yes, 15 exists in list

Method 5: Using Counter() function

Below is the implementation:

Python3

from collections import Counter

test_list = [10, 15, 20, 7, 46, 2808]

frequency = Counter(test_list)

if(frequency[15] > 0):

    print("Yes, 15 exists in list")

else:

    print("No, 15 does not exists in list")

Output

Yes, 15 exists in list

Method 6: Using try-except block

One additional approach to check if an element exists in a list is to use the index() method. This method returns the index of the first occurrence of the element in the list, or throws a ValueError if the element is not present in the list. To use this method, you can wrap the call to index() in a try-except block to catch the ValueError and return False if it occurs:

Python3

def element_exists(lst, element):

  try:

    lst.index(element)

    return True

  except ValueError:

    return False

test_list = [1, 6, 3, 5, 3, 4]

print(element_exists(test_list, 3))

print(element_exists(test_list, 7))

Time complexity: O(n), where n is the length of the list. The index() method iterates through the list to find the element, so the time complexity is linear.

Auxiliary Space: O(1). This approach does not require any additional space.

Approach 7: Using Set
Time complexity: O(1) average case as checking for an element in a set takes constant time on average.
Space complexity: O(n) as it creates a new set from the list to store its elements.

Python3

def check_element_exists_set(lst, target):

  return target in set(lst)

test_list = [1, 6, 3, 5, 3, 4]

target = 3

print("Exists using set: ", check_element_exists_set(test_list, target))

Output

Exists using set:  True

Last Updated :
22 Feb, 2023

Like Article

Save Article

Python hosting: Host, run, and code Python in the cloud!

Arrays are usually referred to as lists. For convience, lets call them arrays in this article.

Python has a method to search for an element in an array, known as index().
We can find an index using:


x = ['p','y','t','h','o','n']
print(x.index('o'))

Arrays start with the index zero (0) in Python:

python-string

Python character array

If you would run x.index(‘p’) you would get zero as output (first index).

Related course:

  • Python Crash Course: Master Python Programming

Array duplicates: If the array contains duplicates, the index() method will only return the first element.

Find multiple occurences

If you want multiple to find multiple occurrences of an element, use the lambda function below.


get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]

Find in string arrays

To find an element in a string array use:


x = ["Moon","Earth","Jupiter"]
print(x.index("Earth"))

You could use this code if you want to find multiple occurrences:



x = ["Moon","Earth","Jupiter","Neptune","Earth","Venus"]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes("Earth",x))


Find in numeric array

The index method works on numeric arrays too:


x = [5,1,7,0,3,4]
print(x.index(7))

To find multiple occurrences you can use this lambda function:



x = [5,1,7,0,3,4,5,3,2,6,7,3,6]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes(7,x))



Время чтения 3 мин.

Существует несколько способов проверки наличия элемента в списке в Python:

  1. Использование метода index() для поиска индекса элемента в списке.
  2. Использование оператора in для проверки наличия элемента в списке.
  3. Использование метода count() для подсчета количества вхождений элемента.
  4. Использование функции any().
  5. Функция filter() создает новый список элементов на основе условий.
  6. Применение цикла for.

Содержание

  1. Способ 1: Использование метода index()
  2. Способ 2: Использование «оператора in»
  3. Способ 3: Использование функции count()
  4. Синтаксис
  5. Пример
  6. Способ 4: использование понимания списка с any()
  7. Способ 5: Использование метода filter()
  8. Способ 6: Использование цикла for

Способ 1: Использование метода index()

Чтобы найти элемент в списке Python, вы можете использовать метод list index(). Список index() — это встроенный метод, который ищет элемент в списке и возвращает его индекс.

Если один и тот же элемент присутствует более одного раза, метод возвращает индекс первого вхождения элемента.

Индекс в Python начинается с 0, а не с 1. Таким образом, через индекс мы можем найти позицию элемента в списке.

streaming = [‘netflix’, ‘hulu’, ‘disney+’, ‘appletv+’]

index = streaming.index(‘disney+’)

print(‘The index of disney+ is:’, index)

Выход

The index of disney+ is: 2

Метод list.index() принимает единственный аргумент, элемент, и возвращает его позицию в списке.

Способ 2: Использование «оператора in»

Используйте оператор in, чтобы проверить, есть ли элемент в списке.

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»)

Выход

Вы можете видеть, что элемент «19» находится в списке. Вот почему оператор in возвращает True.

Если вы проверите элемент «50», то оператор in вернет False и выполнит оператор else.

Способ 3: Использование функции count()

Метод list.count() возвращает количество вхождений данного элемента в списке.

Синтаксис

Метод count() принимает единственный элемент аргумента: элемент, который будет подсчитан.

Пример

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»)

Выход

Мы подсчитываем элемент «21», используя список в этой функции example.count(), и если он больше 0, это означает, что элемент существует; в противном случае это не так.

Способ 4: использование понимания списка с any()

Any() — это встроенная функция Python, которая возвращает True, если какой-либо элемент в итерируемом объекте имеет значение True. В противном случае возвращается False.

main_list = [11, 21, 19, 46]

output = any(item in main_list for item in main_list if item == 22)

print(str(bool(output)))

Выход

Вы можете видеть, что в списке нет «22». Таким образом, нахождение «22» в списке вернет False функцией any(). Если функция any() возвращает True, элемент в списке существует.

Способ 5: Использование метода filter()

Метод filter() перебирает элементы списка, применяя функцию к каждому из них.

Функция filter() возвращает итератор, который перебирает элементы, когда функция возвращает значение True.

main_list = [11, 21, 19, 46]

filtered = filter(lambda element: element == 19, main_list)

print(list(filtered))

Выход

В этом примере мы используем функцию filter(), которая принимает функцию и перечисляет ее в качестве аргумента.

Мы использовали лямбда-функцию, чтобы проверить, совпадает ли входной элемент с любым элементом из списка, и если это так, он вернет итератор. Чтобы преобразовать итератор в список в Python, используйте функцию list().

Мы использовали функцию list() для преобразования итератора, возвращаемого функцией filter(), в список.

Способ 6: Использование цикла for

Вы можете узнать, находится ли элемент в списке, используя цикл for в Python.

main_list = [11, 21, 19, 46]

for i in main_list:

  if(i == 46):

    print(«Element Exists»)

Выход

В этом примере мы прошли список элемент за элементом, используя цикл for, и если элемент списка совпадает с входным элементом, он напечатает «Element exists».

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти настройки родительского контроля
  • Как найти недавно скачанные приложения
  • Как найти брюки под пиджак
  • Как найти давление h2o
  • Если тесто перекисло что делать как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии