-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

5
  • 4
    Have you read the docs? Commented Mar 5, 2018 at 9: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 - idownvotedbecau.se/noresearch Commented Mar 5, 2018 at 9:44
  • 1
    Possible duplicate of How does Python for loop work? Commented Mar 5, 2018 at 9:48
  • The above link asks precisely the same question. Commented Mar 5, 2018 at 9:48
  • Does this answer your question? For Loop in Python Commented Mar 5, 2020 at 21:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.