[Tutor] Use of underscore(_) in place of a variable in target list of for statement

Mats Wichmann mats at wichmann.us
Thu Aug 13 08:52:12 EDT 2020


On 8/13/20 2:54 AM, Alan Gauld via Tutor wrote:
> On 13/08/2020 06:15, Manprit Singh wrote:
> 
>> a, b = 0, 1
>> for _ in range(10):
>>     print(a)
>>     a, b = b, a+b
>>
>> comments on the use of this underscore . 
> 
> This is quite a common Python idiom, I use it occasionally but
> mostly I just use a single-letter variable that never gets used.
> Some argue that introducing an extra name adds complexity,
> others feel that the _ is equally complex for readers who
> may not be familiar with the idiom. Either works, there is
> no difference in the code as far as Python is concerned.

Just to add:

The idiom has become rather a convention: the popular code checkers will
interpret it as you signalling that you actually meant to introduce a
variable that you're not going to reference, and thus refrain from
issuing you a warning about an unused variable.  Syntactically, you have
to put *something* there in the for statement, so this is the compromise
people have settled on.


More information about the Tutor mailing list