Đạt Nguyễn Th&#224;nh - 1 year ago 122
Python Question

# Can't reverse a sublist

``````>>> L = [1, 2, 3, 4]
>>> L[0:2] = [8, 9]
>>> L
[8, 9, 3, 4]
>>> L[0:2].reverse()
>>> L
[8, 9, 3, 4]
``````

Can you explain for me why
`L[0:2].reverse()`
does not change the
`L`
list?

`L[0:2]` creates a new copy of the list, and `L[0:2].reverse()` then reverses that copy. There is a big difference between using assignment to a slice, and to only reading a slice (calling a method, even one that mutates the object, does not turn this into assignment).

You could use slice assignment to assign a reversed copy:

``````L[:2] = L[1:None:-1]
``````

or

``````L[:2] = reversed(L[:2])
``````

This replaces the first 2 elements with those same elements in reverse order:

``````>>> L = [42, 81, 13, 7]
>>> L[:2] = L[1:None:-1]
>>> L
[81, 42, 13, 7]
>>> L[:2] = reversed(L[:2])
>>> L
[42, 81, 13, 7]
``````

Also see Explain Python's slice notation for details on how this works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download