Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python default keyword parameter list

'What You Wrote: '
def append_to(element, to=[]):
    to.append(element)
    return to
'What You Might Have Expected to Happen: '
my_list = append_to(12)
print(my_list)

my_other_list = append_to(42)
print(my_other_list)
#OUTPUT
[12]
[42]

'What Actually Happens'
[12]
[12, 42]

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

'''
What You Should Do Instead
Create a new object each time the function is called, 
by using a default arg to signal that no argument was provided 
(None is often a good choice).
'''
def append_to(element, to=None):
    if to is None:
        to = []
    to.append(element)
    return to


Comment

PREVIOUS NEXT
Code Example
Python :: python string interpolation 
Python :: Local to ISO 8601: 
Python :: get reactions from message discord.py 
Python :: matrix diagonal sum leetcode in java 
Python :: basic python programs 
Python :: flask send email gmail 
Python :: pytube python 
Python :: python tuple and dictionary 
Python :: Looping and counting in python 
Python :: python min key 
Python :: convert string to number python 
Python :: sort 2 lists together python 
Python :: append a dataframe to an empty dataframe 
Python :: python spawn process 
Python :: #remove a sublist from a list-use remove method 
Python :: obtain items in directory and subdirectories 
Python :: close a file python 
Python :: convert dictionary keys to list python 
Python :: seaborn modificar o tamanho dos graficos 
Python :: python extract all characters from string before a character 
Python :: python indentation 
Python :: isolationforest estimators 
Python :: python how to raise an exception 
Python :: sorting decimal numbers in python 
Python :: python syntax errors 
Python :: twitter api python 
Python :: python if not 
Python :: while not command in python 
Python :: create data frame in panda 
Python :: pygame keys keep pressing 
ADD CONTENT
Topic
Content
Source link
Name
7+1 =