Friday, July 10, 2015
Python: list(5) copy a list
Abstract: copy a list
Everything is an object in python. When assigning a name, a reference is created and assigned to the object on the right hand side of the equals sign. For example: The two variables a and b are assigned the same reference. So the operations of ‘a’ would be same with operations on ‘b’.
>>> a=[1,2,3]
>>> b=a
>>> print a, b
[1, 2, 3] [1, 2, 3]
>>> a.append(4)
>>> print a, b
[1, 2, 3, 4] [1, 2, 3, 4]
>>> print id(a),id(b)
140193643099488 140193643099488
If you want copy a list, either function list() or [:] can be used.
>>> b=list(a)
>>> a.append(5)
>>> print a, b
[1, 2, 3, 4, 5] [1, 2, 3, 4]
>>> print id(a), id(b)
140193643099488 140193643174440
>>> b=a[:]
>>> print id(a), id(b)
140193643099488 140193643174080
writing date: 20150710
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment