Reputation: 3694
I'm confused about the iteration process in python
I have:
numbers = [0,1,2,3,4,5]
for i in numbers:
v = numbers
print v
Here is the end of loop
but, in C , C++ , Java we know the line inside the { }
will be executed repeatedly, or if not given curly braces then the next statement after the loop, but I'm confused here.
How many lines will be executed in the iteration?
Does it depend on indent?
Upvotes: 3
Views: 251
Reputation: 102842
Just as an additional note, I think your original code is not doing what I think you want it to do - which is print the numbers 1-5 on their own line. It should be (using Python 3):
numbers = [0,1,2,3,4,5]
for i in numbers:
print(i)
If you run the following code:
numbers = [0,1,2,3,4,5]
v = numbers
print(v)
you'll get:
[0, 1, 2, 3, 4, 5]
Upvotes: 1
Reputation: 137300
Python uses indents to separate blocks of code. Try to think about this specific code as:
numbers = [0,1,2,3,4,5]
for i in numbers: #{
v = numbers
print v
#}
This is completely valid Python code that has comments with curly braces where you would expect them in some different languages.
Python's counterpart of executing single statement is:
numbers = [0,1,2,3,4,5]
for i in numbers: v = numbers
print v
and every loop will execute only v = numbers
(by using ;
you can add statements in the same line, however).
Upvotes: 4
Reputation: 1220
In python, indentation matters a lot. In your code, both of these lines will get executed in each iteration of the for loop:
v = numbers
print v
Upvotes: 1
Reputation: 19037
In Python, the indentation, rather than brackets, determines block scope, so in this example both the indented lines will be executed once per iteration of the loop.
This is the single weirdest thing about Python for programmers coming from the C/Java language families, but you get used to it fairly quickly.
Upvotes: 6