天天看點

python: reverse & reversed 函數

API

這兩個函數都是 對list中元素 反向排序:

list.reverse()

reversed(list)

差別在于:

API 改變原list 傳回值
list.reverse()
reversed(list)

Note:

  • reversed()

    的傳回值類型 并不是list,是以如果需要,要再套上一個

    list()

實驗代碼

import copy
L = ['x', 123, 'abc', 'z', 'xyz']
L_copy = copy.copy(L)

assert list(i for i in reversed(L)) == ['xyz', 'z', 'abc', 123, 'x'] and L == L_copy

L.reverse()
assert L == ['xyz', 'z', 'abc', 123, 'x'] and L != L_copy           

複制