Home > Software engineering >  finding index[] of odd values in a list of integers?
finding index[] of odd values in a list of integers?

Time:01-13

I am trying to find the index value of some odd integers in a list. The program at its current stage only returns a new list containing only the odd integers.

image of my code

This program returns the values [3, 5, 7]. How would i be able to retrieve the index of these odd values instead? For example, [0, 1, 3, 5] for the list shown above.

I have tried "position = dataItem1.index()". I understand that i would need to input an index value within the index brackets.

CodePudding user response:

you can use also use enumerate : it returns the index of the element and the element (also, in python you can loop directly over the elements of a list, no need of while loops). I also encourage the use of .append() to add an element to a list, this is clearly more efficient than concatenate two lists as you do:

l = [0, 3, 2, 3, 4, 7, 6]

def get_odds_index(l):
    res = []
    for idx, val in enumerate(l):
        if val % 2 != 0:
            res.append(idx)
    return res

get_odds_index(l)

CodePudding user response:

Instead of adding the element on that index in the odd list, just add index Like this

def positionOfOdds(arr):
    odds = []
    length = len(arr)
    
    index = 0
    while index < length:
        data = arr[index]
        if data % 2 != 0:
            odds.append(index)
        index  = 1
    return odds

CodePudding user response:

you already know the index, it is the loop variable

def positionOfOdds(arr):
    odds = []
    length = len(arr)
    
    index = 0
    while index < length:
        data = arr[index]
        if data % 2 != 0:
            odds = odds   [index]
        index  = 1
    return odds

CodePudding user response:

You use an array called odds to store the odd numbers, to get the indexes you can create instead an array to store the indexes of the odd numbers, which I called odds_idxs. It should look something like this:

num_list = [0, 3, 2, 3, 4, 7, 6]
def position_of_odds(num_list):
  odds_idxs = []
  length = len(num_list)
  index = 0
  while index < length:
    if num_list[index] % 2 != 0:
      odds_idxs = odds_idxs   [index]
    index = index   1 
  return odds_idxs
  • Related