Hameda169
Hameda169

Reputation: 633

How can I fix redeclared warning?

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

Redeclared 'i' defined above without usage

How can I fix this warning?!!!

Upvotes: 1

Views: 1125

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

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.

Upvotes: 3

Related Questions