How can I fix redeclared warning?

后端 未结 1 1027
借酒劲吻你
借酒劲吻你 2021-01-23 08:34
x = [[] for i in range(5)]
y = [[] for i in range(10)]

Redeclared \'i\' defined above without usage

How can I fix

相关标签:
1条回答
  • 2021-01-23 09:17

    This is a warning since in Python-2.x, the variables in list comprehension are "leaking". It means that these are not locally scoped. For instance:

    >>> i = 'somevalue'
    >>> [[] for i in range(5)]
    [[], [], [], [], []]
    >>> i
    4
    

    Since you use i in both list comprehensions, you thus overwrite the i declared in the first one, with the i of the second one.

    If you want to get rid of this error, you can use different variable names:

    x = [[] for i in range(5)]
    y = [[] for j in range(10)]

    In this case you however do not make use of i and j in the list comprehension. Usually a "throwaway" variable is the underscore (_) or even double underscore (__):

    x = [[] for __ in range(5)]
    y = [[] for __ in range(10)]

    As is written in the "Hitchhikers guide to Python":

    If you need to assign something (for instance, in Unpacking) but will not need that variable, use __ (..)

    Many Python style guides recommend the use of a single underscore _ for throwaway variables rather than the double underscore __ recommended here. The issue is that _ is commonly used as an alias for the gettext() function, and is also used at the interactive prompt to hold the value of the last operation. Using a double underscore instead is just as clear and almost as convenient, and eliminates the risk of accidentally interfering with either of these other use cases.

    0 讨论(0)
提交回复
热议问题