0
Need help with for loops and indexes in python
I'm writing a program where I use for loops to index. Here's an example: word="hello" for letter in word: a=word.index(letter) This gives me the same value of a for the first and the second "l", while I need a to be equal to 2 for the first one and 3 for the second. I guess it considers them to be the same because they are the same letters. Can someone please help me with this problem?
11 Answers
+ 5
Code or didn't happen! đ
+ 4
Sure thing, this is why I wrote "depending on what you're aiming at". enumerate is fine but it iterates on pairs, not singlets. If you need them both - fine. If not, well... simple is better than complex ;)
+ 3
Depending on what you're aiming at, maybe you could iterate through a range of word's length, instead?
word = 'hello'
for letter in range(len(word)):
print(word[letter])
+ 1
Or (to add to Kuba's answer) if you need both the letter and its index at the same time:
for index, letter in enumerate(word):
print('Letter %s at index %s' % (letter, index))
+ 1
Sorry Kuba, but:
for letter in range(len(word)):
print(word[letter])
is just horrible and it does NOT help people to write pythonic code, which is what we should aim at.
This looping way is actually what you would do in C for example, but why do that when we have a faster, clearer and more beautiful way to do it, as pointed out by @Igor B?
Indeed:
"Beautiful is better than ugly. [...]
Simple is better than complex.[...]
There should be one-- and preferably only one --obvious way to do it."
From the Zen of Python...
+ 1
@Edgar: exactly what I suspected, you need both the index and the letter inside the loop, so use the enumerate function. It's almost never the case that you need only the index. And in those cases something like the zip function is a better solution.
0
Thank you both, the program works fine now!
0
Excuse me? I didn't understand the meaning of that last message...
0
Actually, both codes are really useful. However, since I only needed the index, I used Kuba's.
0
w = "hello"
a = []
b = []
j = 0
for i in w:
a.append(j)
b.append(i)
j += 1
d = dict(zip(tuple(a),tuple(b)))
print(d)
------->>> print index of string. keys of dictionary are index. without iterate 2. đđ
0
If you are interested, here is the code for which I needed that. It crypts and decrypts messages.
https://code.sololearn.com/cVT1Kxg7Sjih/?ref=app