Syntax: pointers versus value

Mel Wilson mwilson at the-wire.com
Wed Jul 30 14:08:36 EDT 2003


In article <3F280475.3000500 at mathstat.concordia.ca>,
Danny Castonguay <castong at mathstat.concordia.ca> wrote:
>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_edges(initial_graph, missing_edges):
>	num_m_e = len(missing_edges) #number of missing_edges
>	num_e_pset = 2**num_m_e
>	graphs = []
>	for i in range(0,num_e_pset): #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_graph)
>		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(new_graph)
>	return graphs
>
>--------------------------------------------------------------
>
>the output when I call:
>  ps_of_missing_edges([[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.

   I don't know, but I think you'd better try copy.deepcopy
instead.  Looks like initial_graph and new_graph are sharing
mutable elements.

        Regards.        Mel.




More information about the Python-list mailing list