0

I didn't understand the following two cases:

from __future__ import print_function
if __name__ == '__main__':
    n = int(raw_input())
    print(*range(1,n+1), sep='')

if n is 3

output:123

And in second case with statement,

print(range(1,n+1), sep='')

output:[1, 2, 3]

Didn't understand the function of "*" , is it related to range or print statement?

gokyori
  • 357
  • 4
  • 15
  • `print(range(1,2+1), sep='')` will return `range(1, 3)` – 宏杰李 Feb 02 '17 at 03:45
  • The *(star) operator in a function call unpacks list/tuples etc. See http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-parameters for a larger answer covering it. – Gavin Feb 02 '17 at 03:47

3 Answers3

0

Range returns a tuple, which gets expanded by the * in the function call. It's equivalent to print (1, 2, 3, sep=' '). The * is used to unpack unnamed args. Since they are always passed first keyword args are still allowed as long as any arg doesn't get 2 values.

mmeade
  • 71
  • 2
0

It is the Argument Unpacking feature in Python.

Here is a quick example:

def f(a,b,c):
    print(a,b,c)

f(1,2,3)
f(*[1,2,3])

So print(*(1,2,3)) is equivalent to print(1,2,3)

xmcp
  • 3,347
  • 2
  • 23
  • 36
0

Please see python's Expressions reference

The list's values are being unpacked by the * operator. Here's the quote from the documentation:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

Alex Luis Arias
  • 1,313
  • 1
  • 14
  • 27