# String Looping (Index reports duplicate instead of second iter)

#1

Here’s the code:

``````for letter in "Codecademy":
print letter

print
print

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):
8
i
12
i

but it keeps printing out:
8
i
8
i

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!

#2

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?

#3

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

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

#4

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.

#5

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]

``````

#6

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]
``````

#7

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