-1

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

Mehmaam
  • 573
  • 7
  • 22
Kanishk Tanwar
  • 152
  • 1
  • 10
  • 4
    Have you read the docs? – B001ᛦ Mar 05 '18 at 09:43
  • There's plenty of tutorial material out there in the great web, so it's good to do your research first before asking questions here. So, it's a downvote - http://idownvotedbecau.se/noresearch/ – baduker Mar 05 '18 at 09:44
  • 1
    Possible duplicate of [How does Python for loop work?](https://stackoverflow.com/questions/1292189/how-does-python-for-loop-work) – jpp Mar 05 '18 at 09:48
  • The above link asks precisely the same question. – jpp Mar 05 '18 at 09:48
  • Does this answer your question? [For Loop in Python](https://stackoverflow.com/questions/34340130/for-loop-in-python) – Chandan Mar 05 '20 at 21:17

2 Answers2

2

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.

Rafael
  • 7,002
  • 5
  • 43
  • 52
1

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
mxzlamas
  • 21
  • 3