1. 程式人生 > >python中list的各種方法使用

python中list的各種方法使用

list是python中最常用的資料結構

name_list = ["zhangsan", "lisi", "wangwu"]
# 1.取值和索引
print(name_list[2])
print(name_list.index("zhangsan"))
# 2.修改
name_list[0] = "xiaoming"
# 3.增刪
# append方法在list末尾追加資料
name_list.append("xiaoyang")
# insert 方法在指定索引處插入資料
name_list.insert(1, "xiaohua")
# extend將一個列表追加到另一個列表後面
name_list.extend(["sunwukong", "zhubajie"])

# 4.刪除
# remove刪除指定資料
name_list.remove("xiaohua")
# pop刪除list中的最後一個數據
name_list.pop()
name_list.pop(1)  # 刪除指定索引位置的資料
# clear
name_list.clear()  # 刪除所有資料