Python list function index

Python How to Find Index in a List: The index() Function

To find the index of a list element in Python, use the built-in index() method.

For example, let’s find the first string that equals “Bob” in a list of strings:

names = ["Alice", "Bob", "Charlie"] names.index("Bob") # Returns 1

To find the index of a character in a string, use the index() method on the string.

For example, let’s find the first occurrence of the letter w in a string:

"Hello world".index("w") # returns 6

In this guide, we are going to take a deeper dive into finding the index of an element in Python.

  • How the index() method works.
  • How to get multiple indexes of all similar elements.
  • How to find the index of a list element.
  • How to find the index of a character in a string.
Читайте также:  Html бегущая строка картинок

The index() Method in Python

In Python, a list has a built-in index() method.

This method returns the index of the first element that matches with the parameter.

The syntax for the index() function is as follows:

  • list is the list we are searching for.
  • obj is the object we are matching with.

Let’s see some examples of using the index() method in Python.

How to Find the Index of a List Element in Python

You can use the index() method to find the index of the first element that matches with a given search object.

For instance, let’s find the index of “Bob” in a list of names:

names = ["Alice", "Bob", "Charlie"] names.index("Bob") # Returns 1

The index() method returns the first occurrence of an element in the list. In the above example, it returns 1, as the first occurrence of “Bob” is at index 1.

But this method has a little problem you need to understand.

If the element you are searching for does not exist, this method throws an error that crashes the program if not handled correctly.

For example, let’s search for “David” in the list of names:

names = ["Alice", "Bob", "Charlie"] idx = names.index("David")
ValueError: 'David' is not in list

You certainly don’t want your program to crash when searching for a non-existent value.

To fix this issue, you should check that the element is in the sequence, to begin with. To do this, use the in statement with a simple if-else statement.

names = ["Alice", "Bob", "Charlie"] if "David" in names: idx = names.index("David") else: print("Not found.")

Now the above code no longer throws an error. The index search does not even start if the item is not there.

Now you know how to use the index() method to find an index of an object in a list.

Next, let’s take a look at how you can use a similar approach to finding the index of a character in a string.

How to Find the Index of a String Character in Python

To find an index of a character in a string, follow the same procedure as finding an index in a list.

  • Check if the character is in the string using the in statement.
  • Find the index of the character using the index() method of a string.
sentence = "Hello world" if "x" in sentence: idx = sentence.index("x") else: print("Not found.")

With strings, you can also search for longer substrings or words.

For example, let’s find the index of a substring “wor” in “Hello world”:

sentence = "Hello world" substr = "wor" if substr in sentence: idx = sentence.index(substr) print(idx) else: print("Not found.")

This returns the starting position of the substring “wor”.

Now you understand how to use the index() method in Python.

However, this method only returns the first index. Let’s take a look at how you can get all the indexes instead.

How to Get All Indexes of a List in Python

In the previous examples, you have seen how to get the first index of an element that is equal to the object we are searching for.

However, sometimes you might want to find the indexes of all the elements that equal something.

  1. Couple the elements of a list with an index using the enumerate() function.
  2. Loop over the enumerated elements.
  3. Check if the index, item pair’s item matches with the object you are searching for.
  4. Add the index into a result list.

Here is a generator function that does exactly that:

def indexes(iterable, obj): result = [] for index, elem in enumerate(iterable): if elem == obj: yield index

Or if you want to use a shorthand, you can also use a generator comprehension:

def indexes(iterable, obj): return (index for index, elem in enumerate(iterable) if elem == obj)

Anyway, let’s use this function:

names = ["Alice", "Alice", "Bob", "Alice", "Charlie", "Alice"] idxs = indexes(names, "Alice") print(list(idxs))

As you can see, now this function finds all the indexes of “Alice” in the list.

You can also call it for other iterables, such as a string:

sentence = "Hello world" idxs = indexes(sentence, "l") print(list(idxs))

Conclusion

Today you learned how to get the index of an element in a list in Python. You also saw how to get all the indexes that match with an object.

To recap, use the index() method to find the index of an element in Python. You can use it the same way for lists and strings. It finds the first occurrence of a specified element in the sequence.

  • Implement a function that couples each element with an index.
  • Loop through the coupled elements.
  • Pick the indexes of the elements that match with the search object.

Thanks for reading. I hope you find it useful.

Источник

Функция index() в Python

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

Синтаксис метода в Python:

list.index(element, start, end)

Список параметров

  • element – элемент для поиска;
  • start (необязательно) – начать поиск с этого индекса;
  • end (необязательно) – искать элемент до этого индекса.

Возвращаемое значение из списка

  • Метод возвращает индекс данного элемента в списке.
  • Если элемент не найден, возникает исключение ValueError.

Примечание: Команда возвращает только первое вхождение соответствующего элемента.

Пример 1: Найти индекс элемента

# vowels list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] # index of 'e' in vowels index = vowels.index('e') print('The index of e:', index) # element 'i' is searched # index of the first 'i' is returned index = vowels.index('i') print('The index of i:', index)
The index of e: 1 The index of i: 2

Пример 2: Указатель элемента, отсутствующего в списке

# vowels list vowels = ['a', 'e', 'i', 'o', 'u'] # index of'p' is vowels index = vowels.index('p') print('The index of p:', index)
ValueError: 'p' is not in list

Пример 3: Работа с параметрами начала и конца

# alphabets list alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u'] # index of 'i' in alphabets index = alphabets.index('e') # 2 print('The index of e:', index) # 'i' after the 4th index is searched index = alphabets.index('i', 4) # 6 print('The index of i:', index) # 'i' between 3rd and 5th index is searched index = alphabets.index('i', 3, 5) # Error! print('The index of i:', index)
The index of e: 1 The index of i: 6 Traceback (most recent call last): File "*lt;string>", line 13, in ValueError: 'i' is not in list

Источник

index() in Python

Python Certification Course: Master the essentials

The index() method in Python searches an element in the list and returns its position/index. If there are duplicate elements, then by default, index() returns the position of the first occurrence of the element we are searching for in the list.

An index is a number that defines the position of an element in any given list. In this article, we will look into the function index() which is a single line solution to list index-related queries and then we will go deep into other methods to work with lists and find the index of an element.

Python List Index

Syntax for index() function in Python

The syntax of the list index() method in Python is:

Parameters for index() function in Python

The list index() method can take at most three arguments as discussed below:

  1. element: It specifies the element to be searched in the list. It is a mandatory parameter. Hence it must be provided in the index() method.
  2. start (optional): It is an optional parameter that specifies the starting index from which the element should be searched. The starting index provided must be present in the range of our list; otherwise, index() will throw a ValueError. By default, the index() method searches for any element from the 0 t 0^t 0 t ^h^ index.
  3. end (optional): It is an optional parameter that specifies the position up to which the element should be searched. The end index provided must be in the range of our list. Otherwise, a ValueError will be thrown by the index() method. If «end» is not provided, then by default, the element is searched till the end of the list.

Return Value for index() function in Python

Return Type: int

The index() method in Python returns the index of an element we have specified for it.

Exception of index() function in Python?

If the element is not present in the list, the index() method returns a ValueError Exception. We can handle this error using a try-catch block, as discussed in later examples.

What is index() function in Python?

As we learned above, index() in Python is a method that is used for finding the position or index of any element in a given list. It returns the first occurrence of the element unless we explicitly specify it to return the position after or before a particular index.

It mainly has the following features:

  • It returns the index of the element which we have provided.
  • It only returns the first occurrence of the matching element if any duplicate elements are present.
  • If it does not find any matching element, it raises a value error.

More Examples

We can use index() in Python in the following ways discussed below with relevant examples.

Example 1: Search First Occurrence of any Element

use Index in Python

Output:

Explanation:

In the above example, we have a list ls . We have some values in this list, where a few are repeated as well. Now, if we want to find the first occurrence of any value, we can provide the element in the index() method, like ls.index(5) . So, it returns the index of 5 in the list, which is at position 2 (assuming the elements start from index 0).

What if we want to find any position of 5, apart from the starting position? Here comes the parameter «start» in the index() method.

Example 2: Search Element After a Particular Index

Search element after a particular index

Output:

Explanation:

  • Here, we want to search for 5 5 5 , so we provide the starting index = 6, which means we want our index() method to return the position of the element after the starting index.
  • The index() method will search for 5 in the list, from index 6(inclusive) till the length of the list( = 10), through this statement: element = 5, start = 6 . Once it finds its position, it will return the index of the element.
  • Also, the index() method returns the index, considering the first element at index 0.

Example 3: Search Element After and Before a Particular Index

After having searched for our element at the starting and the ending positions, let us also try to find the position of 5 after a particular index and before a specific index. That is, between a starting and an ending index.

Search element after and before a particular index

Output:

Explanation:

  • In this example we search for ‘5’, after and before a particular index, i.e. between the start and end index. For that, we provid these 3 parameters to our index() method: element = 5, start = 3, end = 7
  • We got that five is present at index 4 (considering the index starts from 0) between the given start and end indexes.

Example 4: Searching for an element not present in our list

Searching for an element not present in our list

Output:

Explanation:

  • Since 20 is not present in our list ‘ls’, a ValueError is thrown by the index() method in Python.
  • Hence, it raised the above exception: ValueError: 20 is not in list
  • However, we can fix this error by using try-except in Python. Let’s see how!

A suitable Fix to Prevent this Error:

To Prevent this Error, we can simply wrap our code block into a try/catch statement:

index in python prevent error

So, the above code returns the index of the value if it is present in the list. Otherwise, it displays the message: «The given value is not present in the list!» .

Conclusion

In this article, we learnt about the index() method in Python, its implementation and its use cases. Let’s recap what we learned till now:

  • Python list index() method returns the position of the first occurrence of a value.
  • It have 3 parameters: element , start and end .
  • element is a mandatory parameter where we pass the element to be searched. Whereas start and end are optional parameters that tell us the range in which the element is to be searched.
  • The element we are searching for must be present in the list. Otherwise index() raises a valueError.

Источник

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