Python: for

for-else expression

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]

is seems to


it = iter(expression_list)

while True:
    try:
        target_list = next(it)
        suite
    except StopIteration:
        break
  • 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.

  • for-else example

def find_item(list, n):
        for item in list:
                if n == item:
                        print('I found it!')
                        break
        else:
                print("I can't find it!")

>>> find_item(range(10), 11)
I can't find it!
>>> 
>>> find_item(range(10), 7)
I found it!
  • 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   
... 
0
1
2
3
4
5
6
7
8
9
  • 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
>>> a
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>> for x in a:
...   if x<0: 
...     a.remove(x)
... 
>>> a
[-4, -2, 0, 1, 2, 3, 4]


>>> a
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>> for x in a[:]:
...     if x < 0: a.remove(x)
... 
>>> a
[0, 1, 2, 3, 4]

user's for-loop

class MyIter:
    def __iter__(self):
        return self
    def next(self):
        if not condition:
            raise StopIteration
        value = calculate next value
        return value

for item in MyIter():
    do something with item

read more

  • The for statement?

  • Understanding Python's "for" statement?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 太陽越來越烈,窗外的樹葉都無精打采的耷拉著腦袋,只有知了還在不知疲倦的叫著。 日子就這樣波瀾不驚的過著,不知不覺已...
    林風起閱讀 630評論 0 4
  • 一、什么是SQLite SQLite是Android系統(tǒng)中自帶的一個簡易高效的數(shù)據(jù)庫,語法與MySql類似,支持事...
    嗟嗟嗟閱讀 346評論 0 0
  • 不知道從什么時候開始,讀書和學習成了一對好基友,似乎不讀書就會變傻,讀書就是學習的代名詞。我只想小聲的說,不至于吧...
    Bookish_陳鍵閱讀 757評論 0 0
  • 蘄艾精油,是一種由蘄艾中提取出來的精油產(chǎn)品。 外觀為淺黃或綠黃色,氣味有些草藥味(蘄艾草的味道),水質(zhì)般粘...
    海芹_09d1閱讀 2,846評論 0 0
  • 事事都順利的話,就沒有意思了,不是嗎? 成功時,可以獲得成就感,不順時,可以記住那種挫敗感。 每個人的工作可能都不...
    萌子莫閱讀 745評論 0 2

友情鏈接更多精彩內(nèi)容