x = [[] for i in range(5)]
y = [[] for i in range(10)]
Redeclared \'i\' defined above without usage
How can I fix
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 thegettext()
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.