Manu Manu - 8 days ago 7
Python Question

How do I reverse a part (slice) of a list in Python?

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] # This works too.
a[2:4].reverse() # But this doesn't work

Answer

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.

Comments