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

Peter Otten __peter__ at web.de
Thu Aug 13 13:30:14 EDT 2020


Manprit Singh wrote:

> 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

To go off on a tangent, I usually use a generator in cases like these:

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

Then you don't need a dummy variable, you can limit the infinite sequence 
with itertools.islice():

from itertools import islice

for n in islice(fib(), 10):
    print(n)




More information about the Tutor mailing list