Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get around declaring an unused variable in a for loop?

If I have a list comprehension (for example) like this:

['' for x in myList] 

Effectively making a new list that has an empty string for every element in a list, I never use the x. Is there a cleaner way of writing this so I don't have to declare the unused x variable?

like image 892
Ramy Avatar asked Mar 29 '11 18:03

Ramy


People also ask

How do you handle unused variables in Python?

To suppress the warning, one can simply name the variable with an underscore ('_') alone. Python treats it as an unused variable and ignores it without giving the warning message.

How do you abort a for loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.

Can you change a variable in a while loop?

Unlike if statements, the condition in a while loop must eventually become False. If this doesn't happen, the while loop will keep going forever! The best way to make the condition change from True to False is to use a variable as part of the Boolean expression. We can then change the variable inside the while loop.

What is an unused variable?

Unused variables are a waste of space in the source; a decent compiler won't create them in the object file. Unused parameters when the functions have to meet an externally imposed interface are a different problem; they can't be avoided as easily because to remove them would be to change the interface.


1 Answers

_ is a standard placeholder name for ignored members in a for-loop and tuple assignment, e.g.

['' for _ in myList]  [a+d for a, _, _, d, _ in fiveTuples] 

BTW your list could be written without list comprehension (assuming you want to make a list of immutable members like strings, integers etc.).

[''] * len(myList) 
like image 98
kennytm Avatar answered Sep 30 '22 19:09

kennytm