Rejo Varghese Rejo Varghese - 1 month ago 8
Python Question

How can I alter the index of loop for a list

I've a list and I want to display the content with index by manually changing the value of index. I've tried to do it in two ways but it is not working.

way 1:

x=['hello','how','are','you','hope','you','are','fine','I','am','doing','work','in','python']
for i,item in enumerate(x):
print (i,item)
if item == 'are':
i+=2


way 2:

x=['hello','how','are','you','hope','you','are','fine','I','am','doing','work','in','python']
for i in xrange(len(x)):
print x[i]
if item == 'are':
i+=2

Answer

Just use a while loop. It's the simplest, clearest and most flexible solution:

i = 0
while i < len(x):
    print x[i]
    if x[i] == 'are':
        i+=1
    i += 1

As you can see, looping over a string is simple and you are completely free to change the index on the fly -- i is just a normal variable. It's not clear what your code was actually meant to do, so the above does what your code would (presumably) have done if it worked: It will skip the word that follows the word "are".