>>> lst=[1]
>>> def f(lst):
lst[0]=3
>>> f(lst)
>>> lst
[3]
私はfでlstを返しませんでした。関数を定義するときにpythonなぜ返り値を使用せずに値が変化する
>>> lst=[1]
>>> def f(lst):
lst[0]=3
>>> f(lst)
>>> lst
[3]
私はfでlstを返しませんでした。関数を定義するときにpythonなぜ返り値を使用せずに値が変化する
これは、リストがPythonで動作するため、リストの関数を送信しないためです。既に存在するリストがあるメモリ内の場所に関数を送り、それを変更することができます。
これはリストがPythonで変更可能で、関数がlst
を変更するためです。実際には、これは紛失したreturn
の声明とは関係がありません。つまり、x = f(lst)
、x
の場合はNone
となります。 lst
にf
を差し替えて実行したい場合は、コピーを送信してください。ここでは例です:
lst = [1, 2, 3]
def fn(lst):
print("in fn")
lst[1] = 10
x = lst[::] # make a copy
print("X before is:", x)
fn(x)
print("X after is:", x)
print("Lst after calling fn with x but before using Lst is:", lst)
fn(lst)
print("Lst after is:", lst)
これは、出力します。
X before is: [1, 2, 3]
in fn
X after is: [1, 10, 3]
Lst after calling fn with x but before using Lst is: [1, 2, 3]
in fn
Lst after is: [1, 10, 3]
リストは変更可能です – Bahrom