Search code examples
pythonpython-3.xgenerator-expression

Why this line does not printing 123...n in python?


Recently I have started learning python programming language and I got stuck while printing 123..n sequence using this:

n=10
print(i for i in range(1,n+1))

I got this output:

<generator object <genexpr> at 0x7f5990f20db0>                                   

Expecting Output:
1234....n
(Note: Only continuous output)


Solution

  • You are attempting to print a generator expression. This is not possible. The parentheses, or lack thereof, indicate a generator expression in Python.

    Instead, you can use a list, indicated by square brackets:

    n = 10
    print([i for i in range(1, n+1)])
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    

    If you wish to print the contents of a generator expression, you can iterate explicitly:

    n = 10
    for i in (i for i in range(1, n+1)):
        print(i)
    

    Or via unpacking the expression and using the sep argument:

    n = 10
    print(*(i for i in range(1, n+1)), sep='')
    12345678910
    

    In this specific example, since you are exhausting the iterator, you can pass a range object directly:

    n = 10
    print(*range(1, n+1), sep='')
    12345678910
    

    The * operator is used for sequence unpacking. It can take any iterable and pass unpacked components to a feeder function, in this case print. It works for print as this specific function can take an arbitrary number of arguments, e.g. try print(1, 2, 3, 4, 5, sep=''). It will not, in contrast, work with list, which requires only one argument.