0
def indexes(word, letter):
    acc=[]
    for i in word:
        for g in letter:
            if g in i:
                acc.append(word.index(i))
    return acc

if i call the function indexes("mississippi","s") the following is returned:

[2, 2, 2, 2]

So, the function returns the correct amount of letters, but it only returns the first index of where "s" is found and fills the list with that index. Any reason why the list doesn't return the index of each "s"?

John Smith
  • 45
  • 2
  • 9
  • because `word.index(i)` will always return the first index of the letter. and you're using the same `word` in each of the loops – Rocky Li Oct 31 '18 at 02:19

3 Answers3

0

The python index() method only returns the first index if an element is present more than once.

As stated here: https://stackoverflow.com/a/6294205/10534842

You can use a list comprehension:

indices = [i for i, x in enumerate(my_list) if x == "whatever"]
samlli
  • 106
  • 5
0

index will always return the first index. You can use enumerate in your function to get the indices of each letter as you iterate:

def indexes(word, letter):
    acc=[]
    for i, c in enumerate(word):
        if c == letter:
            acc.append(i)
    return acc

print(indexes("mississippi","s"))
# [2, 3, 5, 6]
slider
  • 12,810
  • 1
  • 26
  • 42
0

Do with List comprehension,

def indexes(word, letter):
    return [pos for pos, char in enumerate(word) if char == letter]

print(indexes("mississippi","s")) 
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103