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

Manprit Singh manpritsinghece at gmail.com
Thu Aug 13 01:15:34 EDT 2020


Dear sir ,
Consider  a problem where i have to display first ten fibonacci numbers .
if i write a code like this,

a, b = 0, 1
for _ in range(10):
    print(a)
    a, b = b, a+b

This gives the result , but my question is the use of underscore (_) in
place of a variable in  target list of the for statement . Need your
comments on the use of this underscore . Use of underscore in such
situations (where the variable in target list of for statement is not
really needed, as it is not being used inside the block of for loop, i only
have to execute the block n times , in the example above it is 10 times.),
should be preferred or not .

Another alternate is to use while loop like this :
a, b = 0, 1
i = 0
while i < 10:
    print(a)
    a, b = b, a+b
    i = i+1

What should be preferred  in such cases , a for loop with underscore in
variable list or a while loop as given above?  Which practise adheres to
PEP 8 and is more cleaner and readable approach to solve such kind of
problems.

Regards
Manprit singh


More information about the Tutor mailing list