38

Is it possible in python to have a for-loop without index and item? I have something like the following:

list_1 = []
for i in range(5):
    list_1.append(3)

The code above works fine, but is not nice according to the pep8 coding guidelines. It says: "Unused variable 'i'".

Is there a way to make a for-loop (no while-loop) without having neither the index nor the item? Or should I ignore the coding guidelines?

jonie83
  • 1,136
  • 2
  • 17
  • 28
  • 4
    if you won't use the variable, you should use '_' for convention. – myildirim Jul 24 '14 at 08:26
  • 2
    Not an answer to the question in general, but in this specific example, you could do `list_1 = [3] * 5`. – tobias_k Jul 24 '14 at 08:28
  • 1
    I'll elaborate on @tobias_k's comment by saying that, in my opinion, a good rule to keep in mind is that if you find yourself in this kind of situation then for loop is probably not the best way to go. – Tonio Jul 24 '14 at 08:33
  • Can someone point me to _where_ it says this in PEP8? I'm not disagreeing, it's just that I can't find it anywhere [here](http://legacy.python.org/dev/peps/pep-0008/). – SiHa Jul 24 '14 at 09:30
  • @SiHa, install pylint and run it over your code. – Padraic Cunningham Jul 24 '14 at 09:44
  • @Padraic Cunningham: Thanks, useful link, but that wasn't my question. PEP doesn't say anything about this, that I can see. Am I missing something? – SiHa Jul 24 '14 at 10:34
  • I could be wrong but I don't think there is anything in pep8 specifically about having to use `_` when you have an unused variable in a loop, I don't ever get a pep8 coding style violation warning about it either on pycharm. – Padraic Cunningham Jul 24 '14 at 10:47
  • @SiHa I couldn't find it either. This thread also answers a somewhat similar question and some people also said they could not find it: http://stackoverflow.com/questions/11486148/unused-variable-naming-in-python – Tonio Jul 24 '14 at 10:48
  • @PadraicCunningham: Better than that, it doesn't mention unused variables at all ` _ ` or otherwise. @Tonio: Thanks for the link. I think I'll stick with `i` (& `j` etc. in nested loops / comprehensions) though. – SiHa Jul 24 '14 at 11:14

2 Answers2

61

You can replace i with _ to make it an 'invisible' variable.

See related: What is the purpose of the single underscore "_" variable in Python?.

Community
  • 1
  • 1
toine
  • 1,946
  • 18
  • 24
  • 5
    A comment in the accepted answer of the question you linked suggests using __ (double underscore) and this is perfect: it does not collide with gettext and gets rid of the "Unused variable" warning. – Jerther Feb 28 '17 at 15:03
6

While @toine is completly right about using _, you could also refine this by means of a list comprehension:

list_1 = [3 for _ in range(5)]

This avoids the ITM ("initialize, than modify") anti-pattern.

Windowlicker
  • 498
  • 11
  • 18