Python for-loops are iterator-based "for-each" loops. The iterating variable is reassigned at the beginning of each iteration. In other words, the following loop:
In [15]: nums = 1,2,5,8
In [16]: for num in nums:
...: print(num)
...:
1
2
5
8
Is equivalent to:
In [17]: it = iter(nums)
...: while True:
...: try:
...: num = next(it)
...: except StopIteration:
...: break
...: print(num)
...:
1
2
5
8
Similarly, the following loops are equivalent:
In [19]: for num in nums:
...: print("num:", num)
...: num += 1
...: print("num + 1:", num)
...:
...:
num: 1
num + 1: 2
num: 2
num + 1: 3
num: 5
num + 1: 6
num: 8
num + 1: 9
In [20]: it = iter(nums)
...: while True:
...: try:
...: num = next(it)
...: except StopIteration:
...: break
...: print("num:", num)
...: num += 1
...: print("num + 1:", num)
...:
num: 1
num + 1: 2
num: 2
num + 1: 3
num: 5
num + 1: 6
num: 8
num + 1: 9
Note, C-style for-loops don't exist in Python, but you can always write a while-loop (c-style for loops are essentially syntactic sugar for while-loops):
for(int i = 0; i < n; i++){
// do stuff
}
Is equivalent to:
i = 0
while i < n:
# do stuff
i += 1
Note, the difference is that in this case, iteration depends on i
, anything in # do stuff
that modifies i
will impact iteration, whereas in the former case, iteration depends on the iterator. Note, if we do modify the iterator, then iteration is impacted:
In [25]: it = iter(nums) # give us an iterator
...: for num in it:
...: print(num)
...: junk = next(it) # modifying the iterator by taking next value
...:
...:
1
5