5200.8.3.1 在函数中修改 List

Modifying a List in a Function

(When you pass a list to a function…)当你向函数传递一个列表时,函数可以修改这个列表。在函数体内对列表所做的任何更改都是永久性的,这样即使处理大量数据时也能高效工作。

def print_models(unprinted_designs, completed_models):
    """
    Simulate printing each design, until none are left.
    Move each design to completed_models after printing.
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"Printing model: {current_design}")
        completed_models.append(current_design)
def show_completed_models(completed_models):
    """Show all the models that were printed."""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)
 
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
 
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

(This example also demonstrates the idea…) 一个函数应该就只做一件事情

Preventing a Function from Modifying a List

(Sometimes you’ll want…) 如果不希望在函数中改边原数组,就使用一个 copy 版本

function_name(list_name[:])

(Even though you can preserve…) 除非有特殊原因,否则应直接传递列表本身而非其副本,这样更高效,尤其适用于大型列表。