+ 1
Function in Python
How to transfer a list to the function, to change it in the function, it did not change beyond the function?
1 Antwort
+ 6
You can use list slicing to get a different copy of the original list;
a = [1, 2, 3]
b = a[:]
b[0] = 4
print(a[0]) #1
Hence, in a function:
def f(lst):
lst2 = lst[:]
lst2[0] = 4
return lst2
Therefore if you pass a list to the function the original list will be the same.
(I think, I haven't done Python in a long time)