Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a temporary variable in Python 2.7 - memory

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.

like image 965
LinGCode Avatar asked Dec 26 '22 02:12

LinGCode


2 Answers

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.

like image 191
Martijn Pieters Avatar answered Jan 10 '23 09:01

Martijn Pieters


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

tempList = list(haystack) # shallow copy
like image 21
jamylak Avatar answered Jan 10 '23 10:01

jamylak