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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 太阳越来越烈,窗外的树叶都无精打采的耷拉着脑袋,只有知了还在不知疲倦的叫着。 日子就这样波澜不惊的过着,不知不觉已...
    林风起阅读 581评论 0 4
  • 一、什么是SQLite SQLite是Android系统中自带的一个简易高效的数据库,语法与MySql类似,支持事...
    嗟嗟嗟阅读 322评论 0 0
  • 不知道从什么时候开始,读书和学习成了一对好基友,似乎不读书就会变傻,读书就是学习的代名词。我只想小声的说,不至于吧...
    Bookish_陈键阅读 634评论 0 0
  • 蕲艾精油,是一种由蕲艾中提取出来的精油产品。 外观为浅黄或绿黄色,气味有些草药味(蕲艾草的味道),水质般粘...
    海芹_09d1阅读 2,765评论 0 0
  • 事事都顺利的话,就没有意思了,不是吗? 成功时,可以获得成就感,不顺时,可以记住那种挫败感。 每个人的工作可能都不...
    萌子莫阅读 698评论 0 2