String Looping (Index reports duplicate instead of second iter)


Here’s the code:

for letter in "Codecademy":
  print letter

word = "Programming is fun!"

for letter in word:
  if letter == "i":
    print word.index(letter)
    print letter

I expect it to print out (looking at only the second for loop):

but it keeps printing out:

I’ve also swapped the place of print letter and print word.index(letter) but no difference on the console out

Thanks for checking it out!


Please place ``` before and after your code so that others can see what it looks like

Why would 12 be printed, how would the index method have to behave to produce that result, how would it know to do that?
Have you thought about what that method actually promises to do?


I’m used to a different language where an “index” would be a real place in the array. Rather than what I saw in the python docs (after posting… sorry).
Thanks for the formatting tip and sorry bout that too!

Here’s what the doc said, for anyone like me :upside_down_face:

Return the smallest i such that i is the index of the first occurrence of x in the array.


Eh, strings have constant-time lookup by index, not sure how much more real than that it gets.
You didn’t have the index though. You could write a loop to iterate over indexes instead.

I usually avoid access by index. It’s nicer to deal with each value than to explicitly figure out which is the first and last and increasing between them.


haha ok… sorry, growing pains! thanks for your advice!

this is what i was looking for (should’ve just kept going through the lessons! thx again)

word = "Programming is fun!"

for my_index in range(0, len(word)):
  if word[my_index] == "i":
    print my_index
    print word[my_index]


Yeah. The range function is how you’d most conveniently produce numbers counting up from 0. (It defaults to starting at 0, don’t need to specify that)

Another function that can be used here is enumerate which produces pairs of indexes and values which can then be unpacked in a for-loop.
It’s slightly nicer, nothing crazy.

for index, char in enumerate(word):
    if char == 'i':
        print index
        print char

The double variables in the loop might look a bit odd. It’s just unpacking the pairs from enumerate.

Unpacking does some nifty stuff:

a, b = (2, 3)
a, b = [2, 3]
a, b = b, a  # swap values. b, a is actully the same as (b, a)
[a, b, [c, [d]]] = [1, 2, [3, [4]]]  # a=1, b=2, c=3, d=4

# python 3
a, b, *rest = range(10)  # a=0, b=1, 2..9 gets put in rest as a list
[1, 2, *range(3, 10), 10]  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.