简体   繁体   中英

What are the differences between these two lines?

friends = my[:] #1
friends[:] = my #2

both variables can be list or string, ie iterable. I am learning python.

  1. I don't understand how these lines work. Can you explain more about them please?
  2. What are the differences between the two lines?

The first line rebinds friends to a new sequence that is a shallow copy of my (really, it can do anything, but assuming my isn't a memoryview or a weird third party type like a numpy array, that's usually a shallow copy of the whole sequence).

The second line reassigns the contents of friends (which must be mutable) to whatever is in the iterable my (again, weird overrides of friends can change this); my need not be a sequence, a plain iterator would also work, and would be exhausted in the process of populating friends .

In both cases it's a shallow copy (reassigning or appending/popping elements in my after either line won't change friends ). The main difference is that the first line is a rebinding to a new sequence, while the latter changes friends in place. This is important in two ways:

  1. Aliasing: If any other name is bound to the same sequence as friends , the first option doesn't affect the alias (rebinding discards the old reference, so the other aliases keep it, friends doesn't), while the second option modifies the other aliases
  2. Type preservation: The second option doesn't change the type of friends , it just replaces the contents. The first option doesn't care what friends used to be (it could be a non-sequence like int ), it ends up as whatever the slicing produces (eg if my is a list , friends becomes a list afterward).

A concrete example using this setup:

friends = [1, 2, 3]
alsofriends = friends
my = (4, 5, 6)

If you use line 1, then after that line, friends is (4, 5, 6) , and alsofriends is still [1, 2, 3] (it's not related to friends anymore).

If you use line 2, then after that line, friends is [4, 5, 6] (contents from my , but still a list ), and alsofriends is now [4, 5, 6] as well (it's still an alias of friends , and the contents of the shared list now match what was copied from my ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM