Why doesn\'t this work?
# to reverse a part of the string in place
a = [1,2,3,4,5]
a[2:4] = reversed(a[2:4]) # This works!
a[2:4] = [0,0] # Thi
I believe it's worth further elaborating the reasons why
a[2:4].reverse()
does not seem to work.
In addition to the fact that a[2:4] creates a copy in the memory, it should be noted that
list.reverse()
reverses the list in place and its return type is None. If you do
print(a[2:4].reverse())
None is printed. Obviously, if you forcefully do,
a[2:4] = a[2:4].reverse()
Python would raise a TypeError. However, there does exist a copy of a[2:4] in the memory which has been reversed. It's just you have no reference to access it.
On the other hand, a[2:4] = reversed(a[2:4]) works because reversed() returns a reverse iterator.
See comments of the accepted answer for how a[2:4] being different when appearing on the left of assignment.