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?
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.
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.
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.
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.
_
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With