Can someone please help me understand why s[:]=s[::-1]
works perfectly but s[]=s[::-1]
does not?
Also, would this be considered an in-place operation (without extra memory)?
Can someone please help me understand why s[:]=s[::-1]
works perfectly but s[]=s[::-1]
does not?
Also, would this be considered an in-place operation (without extra memory)?
Because s[]
is invalid syntax in Python.
By contrast, s[:]
is the notation for a slice that encompasses the whole list. You could also write s = s[::-1]
. The difference is that this changes the object that the name s
refers to, whereas s[:] = …
changes the contents of the list (and hence is in-place).
s = [1, 2, 3]
id(s)
# 4401507776
s[:] = s[::-1]
id(s)
# 4401507776
s = s[::-1]
id(s)
# 4434730272
(id
gives you the “identity” of an object. Identical objects have the same ID, different objects have different IDs.)