39

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?

9
  • 5
    if you won't use the variable, you should use '_' for convention. Commented Jul 24, 2014 at 8:26
  • 2
    Not an answer to the question in general, but in this specific example, you could do list_1 = [3] * 5. Commented Jul 24, 2014 at 8: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. Commented Jul 24, 2014 at 8: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. Commented Jul 24, 2014 at 9:30
  • @SiHa, install pylint and run it over your code. Commented Jul 24, 2014 at 9:44

2 Answers 2

66

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
9

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.