Python get all index list

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.
Читайте также:  Hash python для чего

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.

Источник

Python: Find List Index of All Occurrences of an Element

Python Find List Index of All Occurences of an Element Cover Image

In this tutorial, you’ll learn how to use Python to find the list index of all occurrences of an element. In many cases, Python makes it simple to find the first index of an element in a list. However, because Python lists can contain duplicate items, it can be helpful to find all of the indices of an element in a list.

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

  • How to find the indices of all occurences of an element in a Python list using:
    • For loops,
    • List comprehensions,
    • NumPy, and
    • more_itertools

    How Python List Indices Work

    Before diving into how to get the index positions of all elements in a Python list, let’s take a quick moment to understand how Python lists are indexed. Because Python lists are ordered container objects, their order remains unless it’s explicitly altered.

    Python list indices start at 0 and continue through to the length of the list minus one. The image below shows how these list indices work in Python:

    How does Python List Indexing Work

    In the following section, you’ll learn how to use the list .index() method to find the index of an element in the list.

    How the Python List Index Method Works

    The Python list .index() has three parameters:

    1. The element to search for,
    2. The index to begin searching at, and
    3. The index to search up to

    The only required argument is the element to search for. By default, Python will search through the entire list, unless explicitly told otherwise.

    Let’s take a look at how this method looks :

    # The list.index() Method list.index( value=, # The value to search for start=, # The index to start at stop= # The index to end at )

    Let’s take a look at an example. We can load a list with different elements in it and find the index of the element using the .index() method:

    # Using the .index() Method a_list = [1,2,3,4,1,2,1,2,3,4] print(a_list.index(1)) # Returns: 0

    In the example above, we applied the .index() method on our list to find the index of the element 1 . The method returned the value 0 , meaning the item exists at the 0 th position. However, we know that the value exists multiple times in the list.

    Why didn’t the method return more than the first index? This is how the method works. Even if an item exists more than once, only the first instance is returned.

    In the following sections, you’ll learn how to get the index positions of all occurrences of an element in a list.

    How to Get Index of All Occurrences of Element in a Python List with a For Loop and Enumerate

    One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.

    Because of this, we can check whether the element matches the element we want to find. If it does, we can add the index position to another list. Let’s see how this works with an example:

    # Using enumerate to Find Index Positions a_list = [1,2,3,4,1,2,1,2,3,4] def find_indices(list_to_check, item_to_find): indices = [] for idx, value in enumerate(a_list): if value == item_to_find: indices.append(idx) return indices print(find_indices(a_list, 1)) # Returns: [0, 4, 6]

    Let’s break down what we did here:

    1. We defined a function that takes a list and an element as input
    2. The function then loops over the retult of the enumerate() function
    3. If the value of the item matches the item we’re looking for, the corresponding index is appended to the list
    4. Finally, the list of all indices is returned

    How to Get Index of All Occurrences of Element in a Python List with more_itertools

    The built-in more_itertools library comes with a number of helpful functions. One of these functions is the locate() function that takes an iterable and a function to evaluate against.

    In order to find the index positions of all elements matching an element, we can use a lambda function that simply checks if that item is equal to the item we want to check against.

    Let’s take a look at an example:

    # Using more_itertools to Find All Occurrences of an Element from more_itertools import locate a_list = [1,2,3,4,1,2,1,2,3,4] def find_indices(list_to_check, item_to_find): indices = locate(list_to_check, lambda x: x == item_to_find) return list(indices) print(find_indices(a_list, 1)) # Returns: [0, 4, 6]

    Let’s break down what we did here:

    1. We defined a function that takes both a list and the element to search for
    2. The function uses the locate() function to use the list we want to search and a lambda function that checks if each item is equal to the value we’re searching for
    3. Finally, the function returns a list of the result

    How to Get Index of All Occurrences of Element in a Python List with Numpy

    NumPy makes the process of finding all index positions of an element in a list very easy and fast. This can be done by using the where() function. The where() function returns the index positions of all items in an array that match a given value.

    Let’s take a look at an example:

    # Using numpy to Find All Occurrences of an Element import numpy as np a_list = [1,2,3,4,1,2,1,2,3,4] def find_indices(list_to_check, item_to_find): array = np.array(list_to_check) indices = np.where(array == item_to_find)[0] return list(indices) print(find_indices(a_list, 1)) # Returns: [0, 4, 6]

    Let’s break down what we did here:

    1. We created a function that takes a list and an element to find
    2. The list is converted into a numpy array
    3. The where() function is used to evaluated the array against our item
    4. We return the 0th index of that resulting array
    5. We convert that array to a list

    How to Get Index of All Occurrences of Element in a Python List with a List Comprehension

    In this section, we’ll take a look at how to use a list comprehension to return a list of indices of an element in a list. This method works the same as the first method, the for loop, except it uses a list comprehension.

    Let’s see how we can convert the for loop into a list comprehension:

    # Using a List Comprehension to Find All Occurrences of an Element a_list = [1,2,3,4,1,2,1,2,3,4] def find_indices(list_to_check, item_to_find): return [idx for idx, value in enumerate(list_to_check) if value == item_to_find] print(find_indices(a_list, 1)) # Returns: [0, 4, 6]

    The method shown above is much cleaner and easier to read than the for loop. In the next section, we’ll take a look at how these different methods compare in terms of speed.

    Which Method is Fastest To Get Index of All Occurrences of an Element in a Python List

    The table below breaks down how long each method took to find the indices of all occurrences in a list of one hundred million elements:

    Comparing Methods of Runtimes for Finding Indices of all Occurrences of an Element in a List

    Conclusion

    In this tutorial, you learned how to find the index positions of all occurrences of an element in a Python list. You learned how to do this using the Python enumerate() function using both for loops and list comprehensions. You also learned how to use the numpy where() function to do and the more_itertools locate() function.

    Additional Resources

    To learn more about related topics, check out the tutorials below:

    Источник

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