iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0
Software Development

學會 Python 不可怕:我每天學一點的 30 天筆記系列 第 10

Day10 : 列表 list 基礎 – 建立、存取、修改元素

  • 分享至 

  • xImage
  •  

今天會提到 Python 最常用的資料結構之一:列表(List)。
列表就像一個「資料的盒子」,可以一次裝很多東西,並且能用索引(index)存取、修改裡面的資料。

1. 建立列表
在 Python 裡,列表用方括號 [] 建立,裡面的元素用逗號 , 分隔:
https://ithelp.ithome.com.tw/upload/images/20250924/201788721i6mbyWMc5.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20250924/20178872M6db45qWvr.png
重點:

  1. 列表可以放字串、數字、甚至混合不同型別
  2. 列表是有順序的,所以可以用「索引」來存取

2. 存取元素(索引 index)
列表的元素有編號,第一個是 0,第二個是 1,依此類推:
https://ithelp.ithome.com.tw/upload/images/20250924/20178872WMSUQFkloz.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20250924/201788720Or6vy1682.png
索引規則:

  1. 正向索引:從 0 開始往右數
  2. 負向索引:從 -1 開始往左數(-1 表示最後一個元素)

負向索引程式範例:
https://ithelp.ithome.com.tw/upload/images/20250924/20178872CdzuztVPwp.png
https://ithelp.ithome.com.tw/upload/images/20250924/20178872P2WCyZ4UIY.png

3. 修改元素
列表是「可變的」——可以更改裡面的內容:
https://ithelp.ithome.com.tw/upload/images/20250924/20178872erNZFfgHIk.png
更改後的結果,就會從cherry變成blueberry
https://ithelp.ithome.com.tw/upload/images/20250924/20178872iMGoBzdtoD.png

4. 新增元素
除了可以修改現有元素,也可以用 append() 或 insert() 新增元素:
https://ithelp.ithome.com.tw/upload/images/20250924/20178872grBkdysT8D.png
新增完後的結果會變成
https://ithelp.ithome.com.tw/upload/images/20250924/20178872MfjKx9ufAL.png
🔑 append() – 加到最後 : append() 的功能是把新元素加到列表的最後面

  1. append() 只有一個參數,就是我要加的值
  2. 新值一定會放在列表的最後面
  3. 用法:列表.append(元素)

🔑 insert() – 插入到指定位置 : insert() 可以把新元素插入到指定的位置(索引),而不是一定放最後

  1. insert() 有兩個參數:索引(位置)→ 要插在哪裡、元素 → 要插入的值
  2. 插入後,原本該位置的元素會往後移一格
  3. 用法:列表.insert(索引,元素)

5. 刪除元素
有好幾種方法可以刪除元素:
(1) del → 用法:del 列表[索引]
意思是直接刪掉指定位置的元素,用索引(位置)來找
https://ithelp.ithome.com.tw/upload/images/20250924/201788720hYpNdCP9w.png
刪除後結果會輸出
https://ithelp.ithome.com.tw/upload/images/20250924/20178872JlJsCdU3IM.png
(2) pop() → 用法:列表.pop() → 預設刪掉最後一個 / 列表.pop(索引) → 刪掉指定位置
https://ithelp.ithome.com.tw/upload/images/20250924/20178872ugpAdvoACF.png
刪完後,最後會只剩banana
https://ithelp.ithome.com.tw/upload/images/20250924/20178872kn5mR6EA68.png
(3) remove() → 用法:列表.remove(值)
意思是直接刪掉指定值,不用管它在哪個位置
https://ithelp.ithome.com.tw/upload/images/20250924/20178872tRup0UUEFk.png
https://ithelp.ithome.com.tw/upload/images/20250924/20178872BHOwqAd2c0.png

6. 用迴圈走訪列表
可以搭配 for 迴圈,依序讀取列表裡的每個元素:
https://ithelp.ithome.com.tw/upload/images/20250924/20178872gYes9yJNbV.png
結果會依序輸出
https://ithelp.ithome.com.tw/upload/images/20250924/20178872GWlTXQCwDk.png
for f in fruits : 這行代表用一個迴圈,依序讀取 fruits 裡的每一個元素,並且把每一個元素暫時存到變數 f 裡。
也就是:
第一次迴圈:f = "apple"
第二次迴圈:f = "banana"
第三次迴圈:f = "cherry"


上一篇
Day9 : 迴圈進階練習 – 巢狀迴圈、break、continue
下一篇
Day11 : 列表應用 – 排序、切片、迴圈處理列表
系列文
學會 Python 不可怕:我每天學一點的 30 天筆記13
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言