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

Alan Gauld alan.gauld at yahoo.co.uk
Thu Aug 13 04:54:13 EDT 2020


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.

> Another alternate is to use while loop like this :
> a, b = 0, 1
> i = 0
> while i < 10:
...
> What should be preferred  in such cases

I'd argue that a while loop is intended for indeterminate numbers
of loops. When you know how many loops you need (or may
need - break etc) you should use a for loop.

At the end of the day it is all about making the code clearly
express your intentions. If you are iterating over a sequence
or you know how many repetitions you need, use a for loop.
If you need to repeat until some condition is true (or forever),
use a while loop.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list