- #1
fog37
- 1,568
- 108
Hello,
I understand that a ##for## loop is intended to repeat the same code a finite and specified number of time. The loop syntax is
for = keyword
i = counter variable
iterable = any iterable (list, tuple, dictionary, range())
statements = body of the loop
in = membership operator
i in iterable = Boolean condition. If true, the loop body is executed. If false, the loop body is not run
My understanding is that the for loop works in the following way under the hood:
Is that correct?
Another way to understand what for loop is that:
I understand a little better the difference between iterables and iterators. I am still unsure of why an iterator is better than a list in the sense that we can selecting the elements of a list using indexing, for example, instead of converting an iterable into a iterator and using the ##next()## function...
Thank you!
I understand that a ##for## loop is intended to repeat the same code a finite and specified number of time. The loop syntax is
For loop:
for i in iterable:
statement(s)
for = keyword
i = counter variable
iterable = any iterable (list, tuple, dictionary, range())
statements = body of the loop
in = membership operator
i in iterable = Boolean condition. If true, the loop body is executed. If false, the loop body is not run
My understanding is that the for loop works in the following way under the hood:
- a counter variable ##i## is automatically created
- the iterable is converted to an iterator via the ##iter()## function
- the ##next()## function is applied to the iterator and each value that ##next()## sifts from the iterator is assigned to the variable ##i##
Is that correct?
Another way to understand what for loop is that:
- A variable ##i## is automatically created and fist assigned as value the first element of the iterable. Because of that, the condition i in iterable is True so the body of the loop is executed
- the for statement is run again and this time the i variable has been updated and assigned the 2nd value inside the iterable, the loop body is executed and so on until the variable ##i## has assumed the last value of the iterable...
I understand a little better the difference between iterables and iterators. I am still unsure of why an iterator is better than a list in the sense that we can selecting the elements of a list using indexing, for example, instead of converting an iterable into a iterator and using the ##next()## function...
Thank you!