1

I am confused by the use of * in random.randint() and could not find any documentation

random.randint( *(1,300) )

vs

random.randint( 1,300 )

random.randint( *300 )
TypeError: randint() argument after * must be a sequence, not int
zero323
  • 305,283
  • 89
  • 921
  • 912
user138645
  • 782
  • 1
  • 6
  • 16
  • 4
    Is that the literal code? It'd make sense if it was `r = [1, 300]; random.randint(*r)`... But a literal tuple being unpacked it kind of odd... I think the link provided by @ecatmur is most likely the answer to your question – Jon Clements Oct 22 '13 at 12:07
  • Yes its not the literal code. The tuple argument is passed to random.randint(). Thanks. – user138645 Oct 22 '13 at 12:08

3 Answers3

6

The * in this context expands the tuple into separate elements. Whereas

random.randint( (1,300) )

would incorrectly pass a tuple as the single argument to random.randint,

random.randint( *(1,300) )

passes each element of the "decorated" tuple as an argument to the function. It's not really useful with a hard-coded tuple, since it would be faster and clearer to drop the * and the parentheses. However, when you have a name that references a tuple, it makes more sense.

range = (1,300)
random_value = random.randint( *range )
chepner
  • 446,329
  • 63
  • 468
  • 610
2

The * is part of Python's function call syntax. The * takes an iterable and adds its elements to the parameters of the function call.

random.randint(*(1,300))

is the same thing as

random.randint(1,300)

The following is a syntax error, because 300 is not an iterable.

random.randint(*300)

The * syntax can sometimes be useful. If you have a list (or some other iterable) x that contains the positional parameters that you want to use in a function call, you can either say:

func(x[0], x[1], x[2])

or, simply:

func(*x)
Ben
  • 675
  • 3
  • 5
1

The use of * in any python's function, means that the sequence that follows * is the arguments list to pass to the function. So,

random.randint(*(1, 300))

is the same that

random.randint(1, 300)

the code

random.randint(*300)

fails because 300 isn't a sequence it's an integer.

johnny
  • 18,831
  • 49
  • 151
  • 252
Raydel Miranda
  • 13,236
  • 2
  • 36
  • 56