Scoping in Python 'for' loops

前端 未结 6 1274
名媛妹妹
名媛妹妹 2020-11-22 03:52

I\'m not asking about Python\'s scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were m

6条回答
  •  时光取名叫无心
    2020-11-22 04:18

    A really useful case for this is when using enumerate and you want the total count in the end:

    for count, x in enumerate(someiterator, start=1):
        dosomething(count, x)
    print "I did something {0} times".format(count)
    

    Is this necessary? No. But, it sure is convenient.

    Another thing to be aware of: in Python 2, variables in list comprehensions are leaked as well:

    >>> [x**2 for x in range(10)]
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    >>> x
    9
    

    But, the same does not apply to Python 3.

提交回复
热议问题