Can anybody help me understand this -
In a function, when I slice the passed list, it creates a new list instead of affecting the callers passed-list.
So in the code below, when I passed 'a' to the function as 'x', and the function slices 'x', it created a new list instead of affecting 'a'.
This seems different behavior specifically for slices... and I just saw that if I execute "a=[1,2]; a=a[1:]", the second 'a' is a new list also.
In a function, when I slice the passed list, it creates a new list instead of affecting the callers passed-list.
So in the code below, when I passed 'a' to the function as 'x', and the function slices 'x', it created a new list instead of affecting 'a'.
This seems different behavior specifically for slices... and I just saw that if I execute "a=[1,2]; a=a[1:]", the second 'a' is a new list also.
def foo1 (x): print("list / ID received by function:", x, id(x)) x = x[1:] print("list / ID after function's slice:", x, id(x)) return x a = ["alpha", "beta"] print("list / ID original:", a, id(a)) b = foo1 (a) print("list / ID returned:", b, id(b)) print("list / ID original:", a, id(a)) >>> list / ID original: ['alpha', 'beta'] 55720416 list / ID received by function: ['alpha', 'beta'] 55720416 list / ID after function's slice: ['beta'] 55720496 list / ID returned: ['beta'] 55720496 list / ID original: ['alpha', 'beta'] 55720416 >>>
Larz60+ write Jul-20-2022, 01:40 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode tags on future posts.
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode tags on future posts.