Swapping elements in lists in python -
i have list , need swap 1st element in list maximum element in list.
but why code 1 work while code 2 doesn't:
code 1:
a = list.index(max(list)) list[0], list[a] = list[a], list[0]
code 2:
list[0], list[list.index(max(list))] = list[list.index(max(list))], list[0]
i thought python first evaluate right-hand side before assigning names on left?
python stores results in multiple targets left right, executing assignment target expression in order.
so second version comes down this:
temp = list[list.index(max(list))],list[0] list[0] = temp[0] list[list.index(max(list))] = temp[1]
note list.index(max(list))
executed after list[0]
altered, , that's stored maximum value.
this documented in assignment statements documenation:
- if target list comma-separated list of targets: object must iterable same number of items there targets in target list, , items assigned, from left right, corresponding targets.
from there on out if each target single target, documentation follows applies left right each target:
assignment of object single target recursively defined follows.
[...]
- if target subscription: primary expression in reference evaluated. should yield either mutable sequence object (such list) or mapping object (such dictionary). next, subscript expression evaluated.
if changed order of assignments code work:
list[list.index(max(list))], list[0] = list[0], list[list.index(max(list))]
because list[list.index(max(list))]
assigned first.
Comments
Post a Comment