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
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
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 )
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)
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.