Understanding List Passing and Modification in Python Functions
This article demonstrates how Python functions can receive list arguments, modify them permanently, and how to pass a copy to prevent changes, illustrating the effects with clear code examples and output results.
When a list is passed to a function, the function can directly access and manipulate the list's contents.
Example:
def send_invitation(experts):
'''Send invitation'''
for expert in experts:
print(expert + ',您好,现邀请您参加 XX 研讨会...')
experts = ['袁孝楠', '黄莉莉']
send_invitation(experts)Running this code prints each expert's invitation.
Because the list is mutable, a function can also modify it, and such modifications persist after the function returns.
Example with modification:
def send_invitation(experts, informed):
'''Send invitation and move items to informed list'''
while experts:
expert = experts.pop()
print(expert + ',您好,现邀请您参加 XX 研讨会...')
informed.append(expert)
experts = ['袁孝楠', '黄莉莉'] # expert list
informed = [] # notified list
print('Before: experts=' + str(experts) + ', informed=' + str(informed))
send_invitation(experts, informed)
print('After: experts=' + str(experts) + ', informed=' + str(informed))The output shows that before the call the lists contain the original values, and after the call experts is empty while informed holds the invited experts, confirming that changes are permanent.
Sometimes we want the original list to remain unchanged. Passing a shallow copy (e.g., experts[:] ) prevents the function from altering the original list.
Example with a copy:
experts = ['袁孝楠', '黄莉莉']
informed = []
print('Before: experts=' + str(experts) + ', informed=' + str(informed))
send_invitation(experts[:], informed)
print('After: experts=' + str(experts) + ', informed=' + str(informed))The result shows that after the call the original experts list is unchanged, while informed contains the invited experts.
While copying protects the original data, creating copies consumes memory and time; for large datasets, passing the original list is more efficient.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.