The "for" statement ******************* The "for" statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object: for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the "expression_list". The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see *Assignment statements*), and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty or an iterator raises a "StopIteration" exception), the suite in the "else" clause, if present, is executed, and the loop terminates. A "break" statement executed in the first suite terminates the loop without executing the "else" clause's suite. A "continue" statement executed in the first suite skips the rest of the suite and continues with the next item, or with the "else" clause if there is no next item. The for-loop makes assignments to the variables(s) in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop: for i in range(10): print(i) i = 5 # this will not affect the for-loop # because i will be overwritten with the next # index in the range Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in function "range()" returns an iterator of integers suitable to emulate the effect of Pascal's "for i := a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]". Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g., for x in a[:]: if x < 0: a.remove(x) Related help topics: break, continue, while
"for" target_object "in" expression_list ":"
"body of the loop"
Points of Interest:
1. Target_object ; Any Python object:
2. Expression_list ; is eval only once.
When eval; yields an iterable object.
Consequently; An "iterator" is created.
3. Loop Body / Suit ; is executed once for each item, provided by the iterator.
Performs nessecery ops on expressions within the loop body, mainly assignments.
When the items are exhausted, the iterator raises a "StopIteration" exception.
The suite moves to "else" clause, if present, is executed, and the loop terminates.
In :%%HTML <iframe width="800" height="250" frameborder="0" src="http://pythontutor.com/iframe-embed.html#code=for%20i%20in%20range(5%29%3A%0A%20%20%20%20print(%22I%20will%20not%20bow!%22%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe>
In :help("range") """ Syntax: range( start, stop, stepsize ) -> range object. """ # a simple example for i in range(5): print("Hello Again!") print("Ok bye!")
Help on class range in module builtins: class range(object) | range(stop) -> range object | range(start, stop[, step]) -> range object | | Return an object that produces a sequence of integers from start (inclusive) | to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. | start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. | These are exactly the valid indices for a list of 4 elements. | When step is given, it specifies the increment (or decrement). | | Methods defined here: | | __contains__(self, key, /) | Return key in self. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __reduce__(...) | helper for pickle | | __repr__(self, /) | Return repr(self). | | __reversed__(...) | Return a reverse iterator. | | count(...) | rangeobject.count(value) -> integer -- return number of occurrences of value | | index(...) | rangeobject.index(value, [start, [stop]]) -> integer -- return index of value. | Raise ValueError if the value is not present. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | start | | step | | stop Hello Again! Hello Again! Hello Again! Hello Again! Hello Again! Ok bye!