34
loading...
This website collects cookies to deliver better user experience
def add_fruit(fruit, box=[]):
box.append(fruit)
return box
add_fruit
function which is responsible for adding the fruit
fruit
and box
weekends = ('saturday', 'sunday',)
weekends[0] = 'Monday' # TypeError: 'tuple' object does not support item assignment
def add_fruit(fruit, box=[]):
box.append(fruit)
return box
red_box = add_fruit("apple")
print(f"red box: {red_box}")
yellow_box = add_fruit("mango")
print(f"yellow box: {yellow_box}")
red box: ["apple"]
yellow box: ["mango"]
red box: ["apple"]
yellow box: ["apple", "mango"]
Python’s default arguments are evaluated once when the function is defined. 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.
add_fruit
function:def add_fruit(fruit, box=None):
if box is None:
box = []
box.append(fruit)
return box
red_box = add_fruit("apple")
print(f"red box: {red_box}")
yellow_box = add_fruit("mango")
print(f"yellow box: {yellow_box}")