Home > Net >  how does indexing work in a for loop when appending a list?
how does indexing work in a for loop when appending a list?

Time:11-24

I´m trying write a function that returns a list with the positions for each capital letter it doesn’t work with when the capital letter in the string is repeated.

def capital_indexes(word):
    cap = []
    for i in word:
        if i == i.upper():
            cap.append(word.index(i))
    return cap
print(capital_indexes("HelloWorld"))

[0, 5]
print(capital_indexes("HoHoHoHo"))

[0, 0, 0, 0]

CodePudding user response:

I think that index method is returning the first occurrence of character.

Maybe you should control the index of letter by an another var like this:

def capital_indexes(word):
    cap = []
    index = 0
    for i in word:
        if i == i.upper():
            cap.append(index)
        index=index 1
    return cap

CodePudding user response:

It doesn't work as expected because the indexmethod returns the first occurrence of the match (some docs here).

So... Let's say your code finds the third H (for instance) in the string HoHoHoHo. Then index asks "Hey, give me the first H" Which happens on position 0 (HoHoHoHo).

I suggest you print what you are iterating over. I say this because the fact that you're calling your item i (usually used for indices) makes me think that maaaaaybe there's a tiny confusion between the index and the element?.

Maybe just renaming your control variable will help a bit:

def capital_indexes(word):
    cap = []
    for letter in word:
        if letter == letter.upper():
            cap.append(word.index(letter))
    return cap

With that in mind, you can now take a look to enumerate, which will give you both the item and the position it's in:

def capital_indexes(word):
    cap = []
    for idx, letter in enumerate(word):
        if letter == letter.upper():
            cap.append(idx)
    return cap

If you want to stick to indices, you have to retrieve the contents of position idx in the string:

def capital_indexes(word):
    cap = []
    for idx in range(len(word)):
        letter = word[idx]
        if letter == letter.upper():
            cap.append(idx)
    return cap
  • Related