4

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good explanation. The alternative is to just not use mutating methods—instead of haystack.extend(iterable) do haystack = haystack + list(iterable) (or haystack = itertools.chain(haystack, iterable) if you don't need a list).
3

tempList and haystack are just two names that you bind to the same list. Make a copy:

tempList = list(haystack) # shallow copy

Comments

1

This is a classic example of the difference of behaviour between lists and standalone variables in Python. This is because tempList = haystack doesn't copy haystack values to tempList, but assigns address of haystack to address of tempList. That is, now you are referring to the same place in memory by two names. So modifying one will modify another. To copy values you can do tempList = list(haystack).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.