Pass a list to diffrerent variables.

Robbie user at domain.invalid
Sun May 2 09:49:40 EDT 2004


Peter Otten wrote:

> user at domain.invalid wrote:
> 
> 
>>When trying to pass the contents from one list to another this happens:
>>
>>list = [1,2,3]
> 
> 
> Don't use list as a name. It hides the builtin list class.
> 
> 
>>list1 = list
>>print list1
>>  [1,2,3]
>>list.append(7)
>>print list1
>>  [1,2,3,7]
>>
>>Whats the easiest way to pass the data in a list, not the pointer, to
>>another variable
> 
> 
>>>>first = [1, 2, 3]
>>>>second = list(first) # create a list from the sequence 'first'
>>>>second.append(4)
>>>>first
> 
> [1, 2, 3]
> 
>>>>third = first[:] # slice comprising all items of the 'first' list
>>>>third.append(5)
>>>>first
> 
> [1, 2, 3]
> 
> 
> Both methods shown above result in a (shallow) copy of the original list.
> 
> Peter

Thanks, that works fine but I am working with a 2d list...
and I dont understand why this happens
d = [[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
d
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
f = list(d)
f
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
d[0][0]="a"
d
[['a', 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
f
[['a', 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
What exactly is this doing? And how can I stop it?



More information about the Python-list mailing list