Skip to content
Advertisement

For loop in Python make issue [closed]

so earlier I am learning c/c++ and use for loops intensively

for ( init; condition; increment ) {
   statement(s);
}

but now I am learning python and I came across python implementation of for loop which is

for num in range(5):
 print(num)

My question is how for loop works in python

1.) Where is initialization?

2.) Where is testing conditions?

3.) Where is the increment?

or else python does not work like c/c++ please explain how the for loop works in python

Advertisement

Answer

I think you need to understand that range is not part of the for loop but is an immutable sequence type.

Range definition:

range(start, stop[, step])

start The value of the start parameter (or 0 if the parameter was not supplied)

stop The value of the stop parameter

step The value of the step parameter (or 1 if the parameter was not supplied)

Python’s for statement iterates over the items of any sequence and hence since range is immutable sequence type what you supply to the for loop is actually a sequence of numbers.

>>> range(5)
[0, 1, 2, 3, 4]

>>> range(3, 7)
[3, 4, 5, 6]

>>> range(5, 0, -1)
[5, 4, 3, 2, 1]

So range creates a list of numbers that then the for loop is using to loop over.

You could also have:

for i in [0, 1, 2, 3, 4]:
    pass

and you have the same result.

Now how the for iterates over the sequence is another question. In short, it uses iterators to do this. Your best friend is to read the docs of the language you are learning.

Have a look here as well there are some more examples.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement