I save 'haystack' in a temporary variable, but when I modify 'haystack', the temporary variable change too. Why? Help please? it's normal? in PHP I didn't have this problem.
# -*- coding:utf-8 -*-
haystack = [1,'Two',3]
tempList = haystack
print 'TempList='
print tempList
iterable = 'hello'
haystack.extend(iterable)
print 'TempList='
print tempList
Return in Console
TempList=
[1, 'Two', 3]
TempList=
[1, 'Two', 3, 'h', 'e', 'l', 'l', 'o']
But I haven't modified the variable 'tempList'.
Help, please.Thanks.
You are not creating a copy of the list; you merely create a second reference to it.
If you wanted to create a temporary (shallow) copy, do so explicitly:
tempList = list(haystack)
or use the full-list slice:
tempList = haystack[:]
You modify the mutable list in-place when calling .extend()
on the object, so all references to that list will see the changes.
The alternative is to create a new list by using concatenation instead of extending:
haystack = [1,'Two',3]
tempList = haystack # points to same list
haystack = haystack + list(iterable) # creates a *new* list object
Now the haystack
variable has been re-bound to a new list; tempList
still refers to the old list.
tempList
and haystack
are just two names that you bind to the same list
.
Make a copy:
tempList = list(haystack) # shallow copy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With