I want to reverse a list from the kth element IN PLACE and here's my code:
list[:] = list[len(list) - k:] + list[:len(list) - k]
I know that this is the right code while the following code is incorrect. Anyone know why?
list = list[len(list) - k:] + list[:len(list) - k]
Thanks!
The difference is a reflection of the assignment syntax as specified in the python language reference. Your first example generates a modified copy of the list and sets the contents of your list to the contents of the copy. The second example generates a modified copy and assigns the
listidentifier to point to that copy.You can see this more clearly by calling
idon your list before and after:In the second case,
listhas a different id because it actually represents a new list object, where the first reuses thelistand only updates the contents.With that being said, notice that in both cases a copy of the list is being made so you aren't really gaining anything. Neither update is truly being calculated in-place. For this reason, in 99% of cases I would go with the second more concise syntax.
Furthermore the 'in place' version involves updating potentially many elements within the list, where just updating the
listidentifier is always a single update. You can see the small performance overhead from the extra copy work with the following experiments: