This question already has answers here:
How does the key argument in python's sorted function work?
(4 answers)
Closed 20 days ago.
In the myFunc function below, where is the (e) argument passed in from? (I hope I'm using the right terminology)
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
the function myFunc is called by cars.sort(key=myFunc) and each item in the list passed as an argument to myFunc. parameter name is not required here as it can work with the positional parameter. but we still need to have one parameter myFunc so that it can receive the passed value.
also the code can be simplified like below by using len() method directly instead of wrapping it in myFunc.
cars.sort(key=len)
Hope this helps.
Related
This question already has answers here:
How to force the default parameter in python
(4 answers)
Call function without optional arguments if they are None
(10 answers)
Closed 1 year ago.
Is there a way to call a function with an argument but have the argument in a way that the default value of the function is used instead? Like
def f(val="hello"):
print(val)
def g(a=Undefined): #replace Undefined with something else
f(a)
>>> g()
hello
The reason is, the called function is not under my control and I want to inherit its default value. Of course I could
def h(a=None):
f(a) if a else f()
or even
def k(a=None):
j = lambda : f(a) if a else f()
j()
since I have to call that function a few times and also pass other parameters. But all that would be much easier if I could just tell the function I want to use its default value.
I could also simply copy paste the default value to my function, but don't want to update my function if the other one changes.
This question already has answers here:
Pass a list to a function to act as multiple arguments [duplicate]
(3 answers)
Closed 1 year ago.
I have a function and I have an array of arguments that I want to pass to the function when calling it like this:
def function(arg):
pass
function(arg)#call
but I want:
target = function
args = list()
output = call(function,args)
I know, that I can do it with Thread, but I want get a return to main Thread
Thread(target=target,args=args).start() # without output :(
The only possible solution I have come up with is
output = exec('function_name('+','.join(args))
P.S. The functions that I call have a variable number of positional and optional arguments
P.P.S. I can't edit function's code
If those are positional arguments you can use function(*args).
This question already has answers here:
What is the pythonic way to avoid default parameters that are empty lists?
(9 answers)
Closed 2 years ago.
I have a function that recursively calls itself to pull out and return things from a dictionary with multiple levels of nested objects (dicts, lists, and other flat [int/string/etc.] data types). At the end of it, it returns a flat 2D list of particular object names, and to do that, the function has an argument that stores the list which is passed to nested calls which then return it with the things it found appended to the list. When called by the user they shouldn't need to pass anything in to set this argument, and the default value for it is an empty list []. However, when I call this function more than once, the list keeps its contents and I end up getting the next call's items appended to the previous calls' results.
That explains the why and the issue. Below is a very simple example function that demonstrates this, without the nested calls:
def test(arg1=[]):
arg1.append('bob')
return arg1
Calling this multiple times results in:
a=test()
a=test()
a=test()
print(a)
>>['bob', 'bob', 'bob']
# Whereas I am expecting it to return:
>>['bob']
I can change the function to below which works around the issue, but I'd like to know the proper way to do this? (or if this is the proper way? - feels kinda dopey)
def test(arg1=[]):
arg1.append('bob')
arg1_ = arg1
arg1 = []
return arg1_
Default parameters are mutable in Python, you can think of them as belonging to the global scope. You want this:
def test(arg1=None):
if arg1 is None:
arg1 = []
arg1.append('bob')
return arg1
This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 2 years ago.
Here, the list is defined as a local variable in the parameter of the function foo, but I'm confused why even on repeated calls the list still remembers it's previous values, why is it acting like a static variable?
def foo(character,my_list = []):
my_list.append(character)
print(my_list)
foo("a")
foo('b')
foo('c')
---- Output ----
['a']
['a','b']
['a','b','c']
When you define a mutable value as default argument, what python does is something like this:
default_list = []
def foo(character, my_list=default_list):
my_list.append(character)
The same happens for any other mutable type (dict for instance).
You can find a very detailed explanation here: https://docs.quantifiedcode.com/python-anti-patterns/correctness/mutable_default_value_as_argument.html
One way you can make an empty list as a default for a list can be:
def foo(character, my_list=None):
if my_list is None:
my_list = []
my_list.append(character)
This is one of the common gotchas:
Python’s default arguments are evaluated once when the function is
defined, not each time the function is called (like it is in say,
Ruby). This means that if you use a mutable default argument and
mutate it, you will and have mutated that object for all future calls
to the function as well.
This question already has answers here:
Can a variable number of arguments be passed to a function?
(6 answers)
Closed 8 years ago.
How do you write a function in Python with variable arguments into the function and return variable number of outputs? Is this even possible with the constraints?
You mean like this. This is quite similar to ellipses in Java. When supplied with a variable amount of arguments, you can unpack these arguments as a list which you can manipulate as you deem necessary.
def func(*args):
print len(args) # num of vars
yes you can, take a look at splat operator
def my_function(*a): #here a will be list or tuple depend wt u passed
# do your stuff with a
**a for dictionary