How do I reverse a part (slice) of a list in Python?
Just use the slice and reverse it.
a[2:4] = a[2:4][::-1]
a[2:4]
creates a copy of the selected sublist, and this copy is reversed by a[2:4].reverse()
. This does not change the original list. Slicing Python lists always creates copies -- you can use
b = a[:]
to copy the whole list.