Как найти элемент в списке python
Перейти к содержимому

Как найти элемент в списке python

  • автор:

Как найти элемент в списке python

In this article, we will discuss how to search a list of objects in Python.

Searching for a particular or group of objects can be done by iterating through a list.

Syntax:

  • class_name is the name of the class
  • object_name is the name of the object

Example 1:

Create a class Car with the following attributes and perform a search operation that returns cars with price less than 10 Lakhs (10,00,000/-).

Python — как найти элемент списка?

Python - как найти элемент списка

Привет всем! Сегодня мы узнаем, как в Python найти элемент списка. Поехали!
В Python можно найти элемент списка с помощью метода index() или с помощью оператора in.
Например, посмотрим на следующий список цветов:

Если мы хотим найти индекс цвета ‘зеленый’ в этом списке, мы можем сделать следующее:

Конечно, если мы попробуем найти, например, желтый цвет — то получим ошибку — ибо у нас нет обработки исключений. Я писал об этом здесь. В данном же случаем обработку исключений можно представить в следующем виде:

Теперь разберемся, как найти поиск элемента списка с помощью оператора in. Для примера берем все тот же список цветов �� Если мы хотим проверить, присутствует ли цвет ‘желтый’ в списке — попробуем следующий код:

Выведет ‘Желтый не имеется в списке цветов’, потому что ‘желтый’ не присутствует в списке colors.

А еще для поиска элемента списка можно использовать функцию enumerate(), которая позволяет итерироваться по списку и одновременно получать индекс нужного элемента. Используется эта функция в случае, если нужно сделать какую-либо операцию над элементом списка и одновременно знать его (этого элемента) индекс.
Для примера — возьмем код, который позволит вывести значение элемента списка и его индекс:

Надеюсь, теперь тема по поиску элемента с списке в Python стала более простой �� Как всегда — в случае возникновения вопросов пишите на почту или в Telegram.

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

There are the following methods to check if an element is in the list in Python.

  1. Using the “index()” method to find the index of an element in the list.
  2. Using the “in operator” to check if an element is in the list.
  3. Using the “count()” method to count the number of occurrences of an element in the list.
  4. Using the “any()” function.
  5. The “filter()” function creates a new list of elements based on conditions.
  6. Using the “for loop”.

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

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.

Output

The list.index() method takes a single argument, the element, and returns its position in the list.

Method 2: Using “in operator”

Use the “in operator” to check if an element is in the list.

Output

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 3: 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

Output

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

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

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

The filter() function returns an iterator that iterates through the elements when the function returns True.

Output

In this example, we use the filter() function that accepts a function and lists it as an argument.

We used the lambda function to check if the input element is the same as any element from the list, and if it does, it will return an iterator.

To convert an iterator to a list in Python, use the list() function.

We used the list() function to convert an iterator returned from the filter() function to the list.

Method 6: Using the for loop

You can find if an element is in the list using the for loop in Python.

Output

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.

Python List Index: Find First, Last or All Occurrences

Python List Index Find First, Last or All Occurrences Cover Image

In this tutorial, you’ll learn how to use the Python list index method to find the index (or indices) of an item in a list. The method replicates the behavior of the indexOf() method in many other languages, such as JavaScript. Being able to work with Python lists is an important skill for a Pythonista of any skill level. We’ll cover how to find a single item, multiple items, and items meetings a single condition.

By the end of this tutorial, you’ll have learned:

  • How the Python list.index() method works
  • How to find a single item’s index in a list
  • How to find the indices of all items in a list
  • How to find the indices of items matching a condition
  • How to use alternative methods like list comprehensions to find the index of an item in a list

Table of Contents

Python List Index Method Explained

The Python list.index() method returns the index of the item specified in the list. The method will return only the first instance of that item. It will raise a ValueError is that item is not present in the list.

Let’s take a look at the syntax of the index() method:

Let’s break these parameters down a little further:

  • element= represents the element to be search for in the list
  • start= is an optional parameter that indicates which index position to start searching from
  • end= is an optional parameter that indicates which index position to search up to

The method returns the index of the given element if it exists. Keep in mind, it will only return the first index. Additionally, if an item doesn’t exist, a ValueError will be raised.

In the next section, you’ll learn how to use the .index() method.

Find the Index Position of an Item in a Python List

Let’s take a look at how the Python list.index() method works. In this example, we’ll search for the index position of an item we know is in the list.

Let’s imagine we have a list of the websites we open up in the morning and we want to know at which points we opened ‘datagy’ .

We can see that the word ‘datagy’ was in the first index position. We can see that the word ‘twitter’ appears more than once in the list. In the next section, you’ll learn how to find every index position of an item.

Finding All Indices of an Item in a Python List

In the section above, you learned that the list.index() method only returns the first index of an item in a list. In many cases, however, you’ll want to know the index positions of all items in a list that match a condition.

Unfortunately, Python doesn’t provide an easy method to do this. However, we can make use of incredibly versatile enumerate() function and a for-loop to do this. The enumerate function iterates of an item and returns both the index position and the value.

Let’s see how we can find all the index positions of an item in a list using a for loop and the enumerate() function:

Let’s break down what we did here:

  1. We defined a function, find_indices() , that takes two arguments: the list to search and the item to find
  2. The function instantiates an empty list to store any index position it finds
  3. The function then loops over the index and item in the result of the enumerate() function
  4. For each item, the function evaludates if the item is equal to the search term. If it is, the index is appended to the list
  5. Finally, this list is returned

We can also shorten this list for a more compact version by using a Python list comprehension. Let’s see what this looks like:

One of the perks of both these functions is that when an item doesn’t exist in a list, the function will simply return an empty list, rather than raising an error.

Find the Last Index Position of an Item in a Python List

In this section, you’ll learn how to find the last index position of an item in a list. There are different ways to approach this. Depending on the size of your list, you may want to choose one approach over the other.

For smaller lists, let’s use this simpler approach:

In this approach, the function subtracts the following values:

  • len(search_list) returns the length of the list
  • 1 , since indices start at 0
  • The .index() of the reversed list

There are two main problems with this approach:

  1. If an item doesn’t exist, an ValueError will be raised
  2. The function makes a copy of the list. This can be fine for smaller lists, but for larger lists this approach may be computationally expensive.

Let’s take a look at another approach that loops over the list in reverse order. This saves the trouble of duplicating the list:

In the example above we loop over the list in reverse, by starting at the last index. We then evaluate if that item is equal to the search term. If it is we return the index position and the loop ends. Otherwise, we decrement the value by 1 using the augmented assignment operator.

Index of an Element Not Present in a Python List

By default, the Python list.index() method will raise a ValueError if an item is not present in a list. Let’s see what this looks like. We’ll search for the term ‘pinterest’ in our list:

When Python raises this error, the entire program stops. We can work around this by nesting it in a try-except block.

Let’s see how we can handle this error:

Working with List Index Method Parameters

The Python list.index() method also provides two additional parameters, start= and stop= . These parameters, respectively, indicate the positions at which to start and stop searching.

Let’s say that we wanted to start searching at the second index and stop at the sixth, we could write:

By instructing the method to start at index 2 , the method skips over the first instance of the string ‘twitter’ .

Finding All Indices of Items Matching a Condition

In this final section, we’ll explore how to find the index positions of all items that match a condition. Let’s say, for example, that we wanted to find all the index positions of items that contain the letter ‘y’ . We could use emulate the approach above where we find the index position of all items. However, we’ll add in an extra condition to our check:

The main difference in this function to the one shared above is that we evaluate on a more “fuzzy” condition.

Conclusion

In this tutorial, you learned how to use the index list method in Python. You learned how the method works and how to use it to find the index position of a search term. You also learned how to find the index positions of items that exist more than once, as well as finding the last index position of an item.

Finally, you learned how to handle errors when an item doesn’t exist as well as how to find the indices of items that match a condition.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *