Swapping elements in lists in python

你离开我真会死。 提交于 2019-12-01 07:40:01

Python stores results in multiple targets from left to right, executing the assignment target expression in that order.

So your second version essentially comes down to this:

temp = list[list.index(max(list))],list[0]
list[0] = temp[0]
list[list.index(max(list))] = temp[1]

Note that the list.index(max(list)) is executed after list[0] was altered, and that's where you just stored the maximum value.

This is documented in the Assignment statements documenation:

  • If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

From there on out it is as if each target is a single target, so the documentation that follows applies from left to right to each target:

Assignment of an object to a single target is recursively defined as follows.

[...]

  • If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

If you changed the order of assignments your code would work:

list[list.index(max(list))], list[0] = list[0], list[list.index(max(list))]

because now list[list.index(max(list))] is assigned to first.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!