-2

I know this question was asked many times on here, but could not find an adequate answer.

I need to find the position of the words in a list, when I run my code it gives me None

Here is the code:

words = ['Banana', 'Banana', 'Apple', 'Apple', 'Pear', 'Peach', 'Grapefruit', 'St', 'Apple']

def get_position(words, type_word):
    for idx, value in enumerate(words):
        if value in words == type_word:
            return idx
        

positions = get_position(words, 'Apple')
print(positions)

Preferred Output:

[2, 3, 8] 

5 Answers5

0

if you use return then function will return the value you want to give back. same is happening here in your code, it is returning the first matched value and not checking further.

either use yield or a temporay list where you saved match result and then return back

def get_position(words, type_word):
    for idx, value in enumerate(words):
        if value == type_word:
            yield idx

or

def get_position(words, type_word):
    matched = []
    for idx, value in enumerate(words):
        if value == type_word:
            matched.append(idx)
    return matched
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

You have to declare an empty list and append the index to the list when you find a match. Then after the loop, you have to return the list. The code will be something like this:

words = ['Banana', 'Banana', 'Apple', 'Apple', 'Pear', 'Peach', 'Grapefruit', 'St', 'Apple']

def get_position(words, type_word):
    ret = []
    for idx, value in enumerate(words):
        if value in words == type_word:
            ret.append(idx)
    return ret
        

positions = get_position(words, 'Apple')
print(positions)
ksohan
  • 1,165
  • 2
  • 9
  • 23
0
outlist = []
def get_position(words, type_word):
    for idx, value in enumerate(words):
        if value == type_word:
            outlist.append(idx)
    return outlist

Anmol Parida
  • 672
  • 5
  • 16
0

You can use list comprehension.

Use:

def get_position(words, type_word):
    return [idx for idx, w in enumerate(words) if w == type_word]

Output:

>>> get_position(words, "Apple")
[2, 3, 8]
Amit Vikram Singh
  • 2,090
  • 10
  • 20
0

Here is another way of solving this issue:

words = ['Banana', 'Banana', 'Apple', 'Apple', 'Pear', 'Peach', 'Grapefruit', 'St', 'Apple']


def get_indexes(lst_from):
    lst = []
    for i in range(len(lst_from)):
        index = lst_from[i:].index('Apple') + i
        if index not in lst:
            lst.append(index)
    
    return lst
Matiiss
  • 5,970
  • 2
  • 12
  • 29