Python串列

串列(list)字面值

    1. []                   # 空串列
    2. [1,2,3]              # 三個項目
    3. [1, [4,5,6]]         # 巢狀串列
    4. [1, "abc", 3]        # 異質串列

內建運算

arr = [1,2,3]

Query:

    1. arr[0]   == 1                   # 索引運算
    2. arr[-1]  == 3                   # 負索引
    3. arr[1:3] == [2,3]               # 切片
    4. arr[0:3] == [1,2,3]             # 切片
    5. arr[:3]  == arr[0:3]            # True
    6. arr[:-1] == arr[0:2]            # True
    7. arr[:]   == [1,2,3]             # 拷貝
    8. arr + [4,5,6] == [1,2,3,4,5,6]  # 串接
    9. arr * 2 == [1,2,3,1,2,3]        # 重複
    10. [x**2 for x in arr]            # 串列表達式 [1,4,9]

Update:

    1. arr[0] = 10                    # 設定 [10,2,3]
    2. arr[0:2] = [111,222,333]       # 切片設定 [111,222,333,3]
    3. arr.reverse()                  # 反轉 [3,2,1]

Create:

    1. arr.append(4)                  # 新增 [1,2,3,4]
    2. arr.extend([4,5,6])            # 批次新增 [1,2,3,4,5,6]

Delete:

    1. del arr[1]                     # 元素刪除 [1,3]
    2. del arr[0:2]                   # 切片刪除 [3]
    3. arr.pop()                      # 刪除末元素 [1,2]
    4. arr.remove(1)                  # 刪除指定元素 [2,3]