J Carroll
J Carroll

Reputation: 1391

Iteration WAS working in my script, now I cant get python to iterate - what happened?

Did my python ide break or something?

import sys

i = 0
sample = ("this", "is", "Annoying!")

for line in sample:
    print i, line
    i + 1

Now gives me...

0 this 
0 is 
0 Annoying!

I THOUGHT, it would give me:

1 this 
2 is 
3 Annoying

I had other scripts that I was working on and it they all just broke - they all have the same line number when they print numerous iterations using the for statement - can someone PLEASE tell me what the heck is going on - very frustrated lol... did Python break? Do I need sleep? What is wrong here?

Upvotes: 0

Views: 155

Answers (8)

Kugel
Kugel

Reputation: 19814

Just step through debugger to see the execution.

Upvotes: 0

PaulMcG
PaulMcG

Reputation: 63709

I suspect you have an indentation problem, that perhaps the i = i + 1 statement is somehow not part of the for-loop.

But Instead of doing your own counter incrementing, better practice is to use enumerate:

for i,line in enumerate(sample):
    print i,line

Upvotes: 4

Adam Crossland
Adam Crossland

Reputation: 14213

The result that you expect would be obtained by using enumerate:

sample = ("this", "is", "Annoying!")
for index, line in enumerate(sample):
    print index, line

I don't see how the code that you posted ever would have worked in any version of Python.

Upvotes: 2

balpha
balpha

Reputation: 50898

While the other answers are correct, this is how you usually do this in python:

sample = ("this", "is", "Annoying!")

for i, line in enumerate(sample):
    print i, line

The enumerate function does exactly what you want: Iterating through your tuple, while at the same time giving you (line) numbers.

Upvotes: 10

John Feminella
John Feminella

Reputation: 311436

This works just fine for me:

>>> import sys
>>> i = 0
>>> sample = ("abc", "def", "ghi")
>>> for line in sample:
...   i = i + 1
...   print i, line
... 
1 abc
2 def
3 ghi

Are you sure you're incrementing and storing the value i? (Your sample omits this, but in another answer you say you did put i = i + 1.) Remember, Python is whitespace-sensitive, so if you did something like this, the result won't be what you expect:

>>> for line in sample:
...   print i, line
... i = i + 1 # <-- This is not part of the loop!

Upvotes: 4

sth
sth

Reputation: 229563

You are calculating i+1 but are not storing the result of that anywhere. Specifically you are not updating i to contain the new value. Use i = i + 1 or i += 1 instead.

Upvotes: 7

mothis
mothis

Reputation: 213

The problem is you're doing "i + 1", not "i=i+1"

Upvotes: 3

watain
watain

Reputation: 5098

You're not incrementing the variable i in your code, you'd need to do something like:

for line in sample:
    i = i + 1
    print i, line

Upvotes: 2

Related Questions