Python return all indexes

Python — Get the indices of all occurrences of an element in a list

To retrieve the indices of all occurrences of a specific element in a list using Python we can use methods like using for loop, using list comprehension, using enumerate() function, using the index() method in a while loop, etc. In this article, we will explore these different methods and perform the operations to get the indices of all occurrences of an element in a list.

Method 1: Using for loop

In this method, we start iterating through the list and comparing each element to the desired element. If the element matches we add its index to the index list.

Algorithm

  • Initialize an empty list called indices to store the indices of occurrences.
  • Iterate through the list using a for loop and the range() function.
  • Check if the current element at index i is equal to the desired element.
  • If it is, append the index i to the indices list.
  • Return the indices list.

Syntax

for i in range(len(lst)): if lst[i] == element: indices.append(i)

Here, in the for loop the variable i iterates over the length of the list and compares each element of the list with the required element. indices.append(i) , appends the index to the indices list if the element matches.

Example

In the below example, we find and print the indices of all occurrences of the element ‘3’ in the list ‘my_list’. The ‘get_indices()’ function is called with the element and the list as arguments, which returns a list of indices. This list is then printed using the ‘print()’ function.

def get_indices(element, lst): indices = [] for i in range(len(lst)): if lst[i] == element: indices.append(i) return indices my_list = [3, 5, 2, 3, 8, 3, 1] element = 3 indices = get_indices(element, my_list) print(indices)

Output

Method 2: Using list comprehension

This method allows us to create a new list that contains the indices of all occurrences of the desired element.

Algorithm

  • Use list comprehension to generate a new list of indices.
  • Iterate through the list using the range() function.
  • Include the index i in the new list if the element at that index matches the desired element.
  • Return the new list.
Читайте также:  Margin properties in css

Syntax

[i for i in range(len(lst)) if lst[i] == element]

Here, the list comprehension checks for each element in the list and compares it with the required element. If it matches we can print the indices.

Example

def get_indices(element, lst): return [i for i in range(len(lst)) if lst[i] == element] my_list = [3, 5, 2, 3, 8, 3, 1] element = 3 indices = get_indices(element, my_list) print(indices)

Output

Method 3: Using the enumerate() function

The enumerate() function is a useful tool in Python that simplifies iterating over a list while keeping track of the index and the corresponding element. This method allows us to directly obtain the indices of all occurrences of the desired element.

Algorithm

  • Utilize list comprehension to create a new list of indices.
  • Iterate over the list using the enumerate() function, which provides both the index i and the element x.
  • Include the index i in the new list if the element x matches the desired element.
  • Return the new list

Syntax

def get_indices(element, lst): return [i for i, x in enumerate(lst) if x == element]

Here, [i for i, x in enumerate(lst) if x == element] is used to iterate over the list lst using enumerate() to obtain both the index and the element, and filters only the indices where the element matches the desired element.

Example

In the below example, we define a function get_indices() that takes an element and a lst as arguments. It uses list comprehension to iterate over the enumerated list lst and checks if each element x is equal to the given element. It returns a list of indices for which this condition is true. In the provided example, the function is called with element = 3 and my_list = [3, 5, 2, 3, 8, 3, 1], resulting in the output [0, 3, 5], which are the indices of all occurrences of the element 3 in the list.

def get_indices(element, lst): return [i for i, x in enumerate(lst) if x == element] my_list = [3, 5, 2, 3, 8, 3, 1] element = 3 indices = get_indices(element, my_list) print(indices)

Output

Method 4: Using the index() method in a while loop

Another approach to finding the indices of all occurrences of an element is by using the index() method in combination with a while loop. This method help us to locate and record the indices incrementally.

Algorithm

  • Initialize an empty list called indices to store the indices of occurrences.
  • Initialize a variable index with a value of −1.
  • Enter a while loop that continues until a ValueError is raised.
  • Inside the loop, attempt to find the next occurrence of the desired element using the index() method.
  • If a match is found, append the index to the indices list and update the index variable to continue searching from the next position.
  • If no match is found, a ValueError is raised, and the loop breaks.
  • Return the indices list
Читайте также:  Php set date header

Syntax

index = lst.index(element, index + 1)

Here, index() method searches for the first occurrence of the given element starting from the index index + 1. It assigns the found index to the variable index. This allows us to locate subsequent occurrences of the element by incrementing the index and searching again

Example

def get_indices(element, lst): indices = [] index = -1 while True: try: index = lst.index(element, index + 1) indices.append(index) except ValueError: break return indices my_list = [3, 5, 2, 3, 8, 3, 1] element = 3 indices = get_indices(element, my_list) print(indices)

Output

Conclusion

In this article, we discussed how we can get the indices of all occurrences of an element in a list using different methods in Python.We explored four different methods to implement this task: using a for loop, list comprehension, the enumerate() function, and the index() method with a while loop. Each method has its own advantages, and the choice depends on personal preference and the specific requirements of the problem at hand.

Источник

Python How to Find all Indexes of an Item in a List

How to Find all Indexes of an Item in a List

Lists are similar to dynamically sized arrays, which are declared in other languages(e.g., vector in C++ and ArrayList in Java). Lists do not have to be homogeneous all of the time, which makes it a very useful tool in Python. DataTypes such as Integers, Strings, and Objects can all be included in a single list. Lists are mutable, which means they can be changed after they’ve been created.

An index refers to a position within an list.

Given a list and item, the task is to print all indexes of occurrences of that item in the list

givenlist = ["this", "is", "the", "new", "way", "to" , "learn" , "python", "which" , "is" ,"easy" ,"is" ] item = is

Explanation:

Here "is" is present at the indices 1,9 and 11

There are several ways to find indices of item in list some of them are:

Method #1: Using For loop and list

Create an empty list. Iterate through each element in the original list using a for-loop.

Append the index of each occurrence of the given item to the empty list.

Below is the implementation:

# Given list givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python", "which", "is", "easy", "is"] # Given item item = "is" # Taking empty list indexes = [] # Loop over indices of elements in givenlist for index in range(len(givenlist)): # if element is equal to given item then append to empty list if givenlist[index] == item: indexes.append(index) # printing the result indexes print("Indexes are : ", *indexes)

Note : Here * is used to print list with spaces

Читайте также:  PHP setAttribute

Method #2 : Using enumerate() function

The built-in function enumerate can be used to get the index of all occurrences of an element in a list ().

It was created to solve the loop counter issue and can be used in these type of problems.

Below is the implementation:

# Given list givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python", "which", "is", "easy", "is"] # Given item item = "is" print("Indexes are :", end=" ") for index, element in enumerate(givenlist): # If the element is equal to item then print its index if element == item: print(index, end=" ")

Method #3: Using list comprehension and range

You can get a list of all valid indices with the range() function and then compare the corresponding value

at each index with the given object.

Below is the implementation:

# Given list givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python", "which", "is", "easy", "is"] # Given item item = "is" print("Indexes are :", end=" ") # Using list comprehension to store indexes in indexes list indexes = [index for index in range( len(givenlist)) if givenlist[index] == item] # print the list print(*indexes)

Method #4 : Using count() function in itertools

We can use itertools count() function to build an iterator for efficient looping that returns evenly

spaced values beginning with the given amount.

You may use it in conjunction with the zip() function to add sequence numbers as shown below.

from itertools import count # Given list givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python", "which", "is", "easy", "is"] # Given item item = "is" print("Indexes are :", end=" ") indexes = [(i, j) for i, j in zip(count(), givenlist) if j == item] # Traverse the indexes list and print only index for i in indexes: print(i[0], end=" ")

Note: Here we need only index so we print only index element in indexes list

Method #5 : Using Numpy

We use numpy.where() function to get indexes of the occurrences of item in given list.

Below is the implementation

import numpy as np # Given list givenlist = ["this", "is", "the", "new", "way", "to", "learn", "python", "which", "is", "easy", "is"] # Given item item = "is" indexes = np.where(np.array(givenlist) == item)[0] print("Indexes are :",*indexes)

Related Programs:

Источник

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