#!/usr/bin/env python3 def compute(base, value): base.append(value) result = sum(base) print(result) if __name__ == '__main__': testlist = [10, 20, 30] compute(testlist, 15) compute(testlist, 25) compute(testlist, 35)
In Python function, parameter passing, if there is a default for the list (list), then we should note, here there is a pit!
The expected output is:
Python3 /home/shiyanlou/listbugtest.py $
75
85
95
but now the program output is:
$ python3 /home/shiyanlou/listbugtest.py
75
100
135
Basic, please refer to: https://blog.csdn.net/ztf312/article/details/81010274
def f(x,li=[]): for i in range(x): li.append(i*i) print (li) print('---1---') f(4) print('---2---') f(5)
expected results:
---1--- [0, 1, 4, 9] ---2--- [0, 1, 4, 9, 16]
Results of the:
---1--- [0, 1, 4, 9] ---2--- [0, 1, 4, 9, 0, 1, 4, 9, 16]
optimization:
def f(x, li=[]): if not li: # If li is not empty, then you go down (empty list); do not go empty = [] for i in range(x): li.append(i * i) print (li) print('---1---') f(4) print('---2---') f(5) print('---3---') f(6)