Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding index of the same elements in a list

Tags:

python

Suppose I have to find each index of letter 'e' in the word "internet":

letter = 'e'
word = 'internet'
idx = word.index(letter)

But this code gives only the first index. How can I find the rest of them?

like image 521
markiisi Avatar asked Oct 05 '11 09:10

markiisi


2 Answers

Try using enumerate in a list comprehension:

[index for (index, letter) in enumerate(word) if letter == 'e']
like image 166
Mark Byers Avatar answered Sep 29 '22 19:09

Mark Byers


Mark's answer is better for a single letter. I'm adding this in case your real substring is longer than a single character.

If you want to use str.index(), it can take an optional start position and will raise a ValueError if the desired substring is not found:

>>> letter = 'e'
>>> word = 'internet'
>>> last_index = -1
>>> while True:
...     try:
...         last_index = word.index(letter, last_index + 1)
...         print last_index
...     except ValueError:
...         break
... 
3
6
like image 37
Johnsyweb Avatar answered Sep 29 '22 19:09

Johnsyweb