python - Why does `mylist[:] = reversed(mylist)` work? -
the following reverses list "in-place" , works in python 2 , 3:
>>> mylist = [1, 2, 3, 4, 5] >>> mylist[:] = reversed(mylist) >>> mylist [5, 4, 3, 2, 1] why/how? since reversed gives me iterator , doesn't copy list beforehand, , since [:]= replaces "in-place", surprised. , following, using reversed, breaks expected:
>>> mylist = [1, 2, 3, 4, 5] >>> i, item in enumerate(reversed(mylist)): mylist[i] = item >>> mylist [5, 4, 3, 4, 5] why doesn't [:] = fail that?
and yes, know mylist.reverse().
cpython list slice assigment convert iterable list first calling pysequence_fast. source: https://hg.python.org/cpython/file/7556df35b913/objects/listobject.c#l611
v_as_sf = pysequence_fast(v, "can assign iterable"); even pypy similar:
def setslice__list_any_any_any(space, w_list, w_start, w_stop, w_iterable): length = w_list.length() start, stop = normalize_simple_slice(space, length, w_start, w_stop) sequence_w = space.listview(w_iterable) w_other = w_listobject(space, sequence_w) w_list.setslice(start, 1, stop-start, w_other) here space.listview call objspace.unpackiterable unpack iterable in turn returns list.
Comments
Post a Comment