473,545 Members | 2,085 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Syntax: pointers versus value

Simple question but I can't find the answer. Using an example:

listA = [1 ,2]
listB = listA
listB.append(3)
#listA now is [1,2,3]

I want to avoid listA's value to change. Clearly, "listB = listA"
creates the problem. listB and listA become two pointers to the same
object. How then, do I duplicate the two objects; ie make a copy of the
object that listA is pointing to and have listB point to that object.

I'm new to python and I love it.

Thank you,

Jul 18 '05 #1
5 1439
On Wed, 30 Jul 2003 12:46:43 -0400, Danny Castonguay
<ca*****@mathst at.concordia.ca > wrote:

Hi!
Clearly, "listB = listA"
creates the problem. listB and listA become two pointers to the same
object.
Exactly.
How then, do I duplicate the two objects; ie make a copy of the
object that listA is pointing to and have listB point to that object.


Use:
listB = listA[:]

Cheers,

Tino

Jul 18 '05 #2
Tino Lange wrote:
Use:
listB = listA[:]


--------------------------------------------------------------------
In the example I have given, it does solve the problem. However, for
some reason I don't understand, it doesn't work in the next example:

def ps_of_missing_e dges(initial_gr aph, missing_edges):
num_m_e = len(missing_edg es) #number of missing_edges
num_e_pset = 2**num_m_e
graphs = []
for i in range(0,num_e_p set): #iteration will stop at 2^num-1
temp_i = i #use temp_i to find i's bit values
new_graph = initial_graph[:]
print 'initial_graph is ' + str(initial_gra ph)
for j in range (0,num_m_e):
if temp_i%2 == 1:
new_graph[missing_edges[j][0]-1].append(missing _edges[j][1])
temp_i = temp_i >> 1
graphs.append(n ew_graph)
return graphs

--------------------------------------------------------------

the output when I call:
ps_of_missing_e dges([[2,3],[1],[1]], [[2,3],[3, 2]])
is:
initial_graph is [[2, 3], [1], [1]]
initial_graph is [[2, 3], [1], [1]]
initial_graph is [[2, 3], [1, 3], [1]]
initial_graph is [[2, 3], [1, 3], [1, 2]]

--------------------------------------------------------------
Therefore, somehow initial_graph's value changes even though the
assignment is new_graph = initial_graph[:]

Assuming that the assignment does it's job, then I don't see how
initial_graph's value changes.
Thank you,

Jul 18 '05 #3
On Wed, 30 Jul 2003 13:46:29 -0400, Danny Castonguay
<ca*****@mathst at.concordia.ca > wrote:
new_graph = initial_graph[:]
initial_graph is [[2, 3], [1], [1]]
initial_graph is [[2, 3], [1], [1]]
initial_graph is [[2, 3], [1, 3], [1]]
initial_graph is [[2, 3], [1, 3], [1, 2]]


Hi!

Now you have lists in lists. This is another situation.

new_graph = initial_graph[:] will really make a copy of the outer list
- but this outer list contains no values but once again pointers to
other objects.

Use the copy-module for nested copy things like that:
http://www.python.org/doc/current/lib/module-copy.html

Cheers,

Tino

Jul 18 '05 #4
Danny Castonguay <ca*****@mathst at.concordia.ca > writes:
Simple question but I can't find the answer. Using an example: [...] object. How then, do I duplicate the two objects; ie make a copy of
the object that listA is pointing to and have listB point to that
object.

[...]

http://www.python.org/doc/FAQ.html#4.38
John
Jul 18 '05 #5
>>>>> "Danny" == Danny Castonguay <ca*****@mathst at.concordia.ca > writes:

Danny> I want to avoid listA's value to change.

There are several ways

listB = listA[:]

listB = [x for x in listA]

import copy
listB = copy.copy(listA )
listB = copy.deepcopy(l istA)

These don't all do the same thing, but all satisfy the example you
posted, eg
listA = [1 ,2]
listB = listA[:]
listB.append(3)
listA [1, 2]

So far so good, but consider this case
listA = [[],1]
listB = listA[:]
listB[0].append(12) # changing the list at listB[0]
listB [[12], 1] listA [[12], 1]

Sneaky, eh? So the 'listB = listA[:]' made a copy of the list, but
not of the elements of the list. This is a shallow copy, and you
should get the same behavior from copy.copy.

Note that this is related to mutable and immutable objects in python.
In the example above, I didn't replace the first item of the list, I
changed it. Since both listA and listB contained the same object as
their first element, changing one changes the other. If I had
replaced that object in listB, nothing would have happened to listA
listA = [[],1]
listB = listA[:]
listB[0] = 12 # replacing the object, not changing it
listB [12, 1] listA [[], 1]
If you want to avoid this, use deepcopy.
import copy
listA = [[],1]
listB = copy.deepcopy(l istA)
listB[0].append(12)
listB [[12], 1] listA

[[], 1]

The behavior of mutable objects bites everyone a few times when they
begin learning python, so welcome to the club!

John Hunter

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3317
by: Jan van Veldhuizen | last post by:
The UPDATE table FROM syntax is not supported by Oracle. I am looking for a syntax that is understood by both Oracle and SqlServer. Example: Table1: id name city city_id 1 john newyork null
8
4321
by: tom | last post by:
I am new to SQL administration. >From a list of IDs that are the primary key in one table (i.e. Customer Table), I want to make changes in tables that use those IDs as a foreign key. Basically I want to say: If fk_ID is in list then do these statements to that record
4
2047
by: Aaron Walker | last post by:
Greetings, I'm attempting to write my first *real* template function that also deals with a map of strings to member function pointers that is making the syntax a little tricky to get right. The function in question: 36: template <typename Container, 37: typename OutputIterator,
53
4516
by: Alf P. Steinbach | last post by:
So, I got the itch to write something more... I apologize for not doing more on the attempted "Correct C++ Tutorial" earlier, but there were reasons. This is an UNFINISHED and RAW document, and at the end there is even pure mindstorming text left in, but already I think it can be very useful. <url:...
46
2214
by: TTroy | last post by:
Hi, I'm just wondering why people/books/experts say "the function returns a pointer to.." or "we have to send scanf a pointer to.." instead of "the function returns the address of.." or "we have to send scanf the address of.." Isn't the lvalue called a POINTER TO and the (r)value called the ADDRESS OF?
2
1884
by: bor_kev | last post by:
Hi, First of all, i want to use the new managed class syntax and STL.NET under Microsoft Visual (C++) Studio 2005 Beta. I read in a Microsoft article(http://msdn.microsoft.com/VISUALC/default.aspx?pull=/library/en-us/dnvs05/html/stl-netprimer.asp) that i am suposed to include : #include <cli/vector> #include <algorithm>
6
1266
by: stork | last post by:
C++ is always evolving. Within C++, there tend to be two communities. There is the community pushing for performance features, getting ever closer to the metal, and then, there is the applications community. The applications community would, in general, prefer C++ to become more high level - adding things like garbage collectors, improved...
64
3380
by: Zytan | last post by:
I know there are no pointers in C#, but if you do: a = b; and a and b are both arrays, they now both point to the same memory (changing one changes the other). So, it makes them seem like pointers. Can someone please explain why? thanks. Zytan
9
1359
by: parag_paul | last post by:
Hi all I am seeing the following code in one place standalone line in some function , { (void*) new (h) Class_Name(xip, virobj, type, true); } Does it make h an object of the Class_Name class
0
7467
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7656
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7419
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3450
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3442
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1879
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1014
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
703
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.