0

Please, can somebody explain to me why this prints a list with both 1 & 2 in it instead of just 1in the list?

def e(x, list = []): list.append(x) return(list) Y = e(1) Z = e(2) print(Y)

6th Apr 2019, 4:31 AM
Thimira Rathnayake
Thimira Rathnayake - avatar
2 Respuestas
+ 8
Because each of the function calls changes the default parameter "list" of the function. It's always the same list that the numbers are appended to, so with each function call, the list is changed. Normally, you could prevent that by explicitly turning the default parameter into a new list in the function: def e(x, list_ = []): list_ = list(list_) list_.append(x) return(list_) Y = e(1) Z = e(2) print(Y) #[1] However that won't work if your list has the name "list". That's another reason why "list" should never be used as a variable name
6th Apr 2019, 5:12 AM
Anna
Anna - avatar
+ 2
Thanks Anna
6th Apr 2019, 5:18 AM
Thimira Rathnayake
Thimira Rathnayake - avatar