---
# System prepended metadata

title: Python List Reverse 的幾種方式

---

# Python List Reverse 的幾種方式

## `List.reverse()`
```python=
l1 = [110, 220, 330, 440, 550]
print("l1: ", l1)
l1.reverse() # 原地reverse
print("l1: ", l1)

# l1:  [110, 220, 330, 440, 550]
# l1:  [550, 440, 330, 220, 110]
```

## `List[::-1]`
```python=
l2 = [110, 220, 330, 440, 550]
print("l2: ", l2)
l2 = l2[::-1] # 原地reverse
print("l2: ", l2)

# l2:  [110, 220, 330, 440, 550]
# l2:  [550, 440, 330, 220, 110]
```

## 不起作用的 def 內部 `List[::-1]`
```python=
def reverse3(l):
    print(l, "in function")
    l = l[::-1] # 內部物件複製一份，不影響外面
    print(l, "in function")

l3 = [110, 220, 330, 440, 550]
print("l3: ", l3)
reverse3(l3) # 所以沒有reverse的效果
print("l3: ", l3) 

# l3:  [110, 220, 330, 440, 550]
# [110, 220, 330, 440, 550] in function
# [550, 440, 330, 220, 110] in function
# l3:  [110, 220, 330, 440, 550]
```

## def 內部 `List[::-1]`
```python=
def reverse4(l):
    print(l, "in function")
    l[:] = l[::-1] # 改變物件的值
    print(l, "in function")

l4 = [110, 220, 330, 440, 550]
print("l4: ", l4)
reverse4(l4)
print("l4: ", l4)

# l4:  [110, 220, 330, 440, 550]
# [110, 220, 330, 440, 550] in function
# [550, 440, 330, 220, 110] in function
# l4:  [550, 440, 330, 220, 110]
```



[**資料參考**](https://stackoverflow.com/questions/57152755/difference-between-nums-nums-1-and-nums-nums-1)