Home > other >  Some doubt the python sliced
Some doubt the python sliced

Time:09-21

A=[1, 2, 3]
B=a [:]
This changes the value of the b a value will not change, can discover slice (__getitem__?) The return value and original list does not share the same memory

So why
A [:]=[4, 5, 6]
To output a, a, they became [4, 5, 6]?

CodePudding user response:

B=a b value changes will not affect a, because just have a data, b b is not a
A [starting position, the position of termination, interval]
When using a [:], is redefined the list, the following
A=[1, 2, 3]
B=a
B [2]=4
Print # 4-trichlorobenzene [1] (b)
# print (a) [1, 2, 3]
A [:]=# (4 and 6) is equal to the center definition: a=(4 and 6)
# print (a) (4 and 6)

CodePudding user response:

Own answer, replication and output respectively called __setitem__ () and the __getitem__ () two different magic methods

CodePudding user response:

B=a is an assignment statement, does not mean the two equivalent, is to have a first, only then has b
You move the b, a sure don't change
Also, you use a simple [:] is a waste of expression, a [:] is equivalent to a
  • Related