How do I implicitly define a parameter to an empty list?
Question:
In the code below, I’ve been wondering how we could tell if a parameter, b
, is given.
The problem is that the third call of func
does not retain [5]
in a newly created list but rather some pointer in the start that b
is pointing to. I’m guessing this is defined before in the program stack entering func
call itself, so the calling and returning of func
would not change b
…?
Any insight is appreciated.
def func(a, b=[]):
b.append([a])
print(b)
return b
func(3)
func(4, [])
func(5)
Answers:
The best way is to assign the default value of b to something arbitrary (usually None
) then check if b is defined that way:
def func(a, b=None):
if b is None:
b = []
b.append([a])
print(b)
return b
func(3)
func(4, [])
func(5)
You can define b to a default value, e.g. b=None
, and then pick either the value of b if given, or pick an empty list.
def func(a, b=None):
lst = b or []
lst.append([a])
print(lst)
return lst
func(3)
#[[3]]
func(4, [])
#[[4]]
func(5)
#[[5]]
In the code below, I’ve been wondering how we could tell if a parameter, b
, is given.
The problem is that the third call of func
does not retain [5]
in a newly created list but rather some pointer in the start that b
is pointing to. I’m guessing this is defined before in the program stack entering func
call itself, so the calling and returning of func
would not change b
…?
Any insight is appreciated.
def func(a, b=[]):
b.append([a])
print(b)
return b
func(3)
func(4, [])
func(5)
The best way is to assign the default value of b to something arbitrary (usually None
) then check if b is defined that way:
def func(a, b=None):
if b is None:
b = []
b.append([a])
print(b)
return b
func(3)
func(4, [])
func(5)
You can define b to a default value, e.g. b=None
, and then pick either the value of b if given, or pick an empty list.
def func(a, b=None):
lst = b or []
lst.append([a])
print(lst)
return lst
func(3)
#[[3]]
func(4, [])
#[[4]]
func(5)
#[[5]]