Python: Why does a slice work this way?

The official Python tutorial (2.7) says that a slice makes a shallow copy of a list (e.g.), and each element in the slice is a reference to the original list object.

For example, performing

a = [1,2,3] a[:][0] = 2 

will not change the actual value, because only the first element in the slice refers to a new object (which is 2).

However, making

 a[:] = [] # or any other list 

really change the list.

Can someone explain this?

+7
python
source share

No one has answered this question yet.

See similar questions:

74
How does assignment work with Python list slice?

or similar:

5504
Does Python have a ternary conditional operator?
5231
What are metaclasses in Python?
4473
Calling an external command in Python
3790
How can I safely create a subdirectory?
3602
Does Python have a "contains" substring method?
3119
What is the difference between Python list methods that are added and expanded?
2959
Understanding Slice Designation
2818
Finding an index of an element with a list containing it in Python
2097
Is there a way to run Python on Android?
288
Understanding dict.copy () - shallow or deep?

All Articles