Expanding tuples into arguments
myfun(*some_tuple)
does exactly what you request. The *
operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.
tuples as function arguments
For convenience, Python constructs a temporary tuple as needed for an assignment statement. Thus, all three of your assignment statements are exactly the same once they reach data movement.
A function call is not an assignment statement; it's a reference mapping. Therefore, the semantics are different.
If you want Python to unpack your tuple into two separate arguments, use the *
operator:
f(*(2, 3))
Expand tuple into arguments while casting them?
Yeah, that's doable:
blah = random.randint(*map(int, minmax))
Use map(int, ...)
to perform the type conversion.
How to pass tuple as argument in Python?
Add more parentheses:
li.append((3, 'three'))
Parentheses with a comma create a tuple, unless it's a list of arguments.
That means:
() # this is a 0-length tuple
(1,) # this is a tuple containing "1"
1, # this is a tuple containing "1"
(1) # this is number one - it's exactly the same as:
1 # also number one
(1,2) # tuple with 2 elements
1,2 # tuple with 2 elements
A similar effect happens with 0-length tuple:
type() # <- missing argument
type(()) # returns <type 'tuple'>
Expanding tuples in python
If you want to use the format method instead, you can just do:
"{0}{2}{3}{1}".format(a, b, *tup)
You have to name every paramater after tup
because the syntax for unpacking tuples to function calls using *
requires this.
python tuples: unpacking into a list using *args
You can use the list.extend
method instead:
def add_grades(*args):
grades.extend(args):
return grades
Expanding tuple arguments while casting to different types
If you use Python 3.8+, you can use assignment expression :=
def foo():
return ('s', '1')
x, y = (v:=foo())[0], int(v[1])
print(x, y)
Prints:
s 1
How to pass tuple as arguments in order to sequentially apply functions with multiple return values in stable Rust?
You can't do that exactly in stable, but you can cover most of the functions with a macro:
trait Apply<Args> {
type Output;
fn apply(&self, args: Args) -> Self::Output;
}
macro_rules! impl_apply {
// Empty case
() => {};
($first_generic:ident $($other_generics:ident)*) => {
impl_apply!($($other_generics)*);
impl<$first_generic, $($other_generics,)* Ret, Func>
Apply<($first_generic, $($other_generics,)*)>
for Func
where
Func: Fn($first_generic, $($other_generics,)*) -> Ret,
{
type Output = Ret;
#[allow(non_snake_case)]
fn apply(
&self,
($first_generic, $($other_generics,)*): ($first_generic, $($other_generics,)*),
) -> Self::Output {
self($first_generic, $($other_generics,)*)
}
}
};
}
impl<Ret, Func> Apply<()> for Func
where
Func: Fn() -> Ret,
{
type Output = Ret;
fn apply(&self, (): ()) -> Self::Output {
self()
}
}
impl_apply!(A B C D E F G H I J K L M);
Playground.
This macro covers all functions up to 13 arguments.
Pass in tuple to multi-argument function
As the error message states, Python does not allow you to have unnamed arguments after *arg
.
Therefore, you need to explicitly name third
:
>>> def producer():
... return ('a','b')
...
>>> def consumer(first, second, third):
... print first+second+third
...
>>> arg = producer()
>>> consumer(*arg, third='c')
abc
>>>
Related Topics
What Does Asterisk * Mean in Python
Tkinter.Tclerror: Image "Pyimage3" Doesn't Exist
Call a Function from Another File
How to Use Python Requests to Fake a Browser Visit A.K.A and Generate User Agent
Using 'Try' VS. 'If' in Python
Remove Duplicates by Columns A, Keeping the Row with the Highest Value in Column B
How to One Hot Encode in Python
Creating a Symbolic in Shared Volume of Docker and Accessing It in Host MAChine
Why Does Loading the Libc Shared Library Have "'Libraryloader' Object Is Not Callable" Error
"Command Not Found" Using Line in Argument to Os.System Using Python
How to Install Writable Shared and User Specific Data Files with Setuptools
Using Python Subprocess.Call() to Launch an Ncurses Process
How to Run Python Script in Cron
How to Direct Output to a File When There Are Utf-8 Characters