For loop in Python make issue

Question:

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

Asked By: Kanishk Tanwar

||

Answers:

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.

Answered By: Rafael

it is often recommended to use enumerate() instead of in range(). It
Works like this:

my_list = ["first_item","second_item","third_item"]
for i, item in enumerate(my_list):
    print(i)
    print(item)

[enter image description here][1]

Output:

0
first_item
1
second_item
2
third_item
Answered By: mxzlamas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.