Why are slices in Python 3 still copies and not views?

后端 未结 2 538
面向向阳花
面向向阳花 2020-12-13 00:03

As I only now noticed after commenting on this answer, slices in Python 3 return shallow copies of whatever they\'re slicing rather than views. Why is this still the case? E

2条回答
  •  囚心锁ツ
    2020-12-13 00:25

    As well, the fact that you can use assignment to slices to modify the original list, but slices are themselves copies and not views.

    Hmm.. that's not quite right; although I can see how you might think that. In other languages, a slice assignment, something like:

    a[b:c] = d
    

    is equivalent to

    tmp = a.operator[](slice(b, c)) # which returns some sort of reference
    tmp.operator=(d)        # which has a special meaning for the reference type.
    

    But in python, the first statement is actually converted to this:

    a.__setitem__(slice(b, c), d)
    

    Which is to say that an item assignment is actually specially recognized in python to have a special meaning, separate from item lookup and assignment; they may be unrelated. This is consistent with python as a whole, because python doesn't have concepts like the "lvalues" found in C/C++; There's no way to overload the assignment operator itself; only specific cases when the left side of the assignment is not a plain identifier.

    Suppose lists did have views; And you tried to use it:

    myView = myList[1:10]
    yourList = [1, 2, 3, 4]
    myView = yourList
    

    In languages besides python, there might be a way to shove yourList into myList, but in python, since the name myView appears as a bare identifier, it can only mean a variable assignemnt; the view is lost.

提交回复
热议问题