

> 📖 **一起读书吧!** 加入《Python编程:从入门到实践》共读营 👉 [点击参加](https://mp.weixin.qq.com/s/ehe2vMrfAFscRLqbM9TF-g)本讲内容
- 列表的创建与索引访问
- 修改、添加和删除元素
- 组织列表(排序、反转)
- 使用列表时避免索引错误
学习目标
用列表管理有序数据 🛒
1. 什么是列表
列表是有序的可变序列,可以存储任意类型的元素。
1 2 3
| bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles)
|
官方文档:5.1. More on Lists — 列表是可变序列。
2. 访问列表元素
1 2 3 4 5 6 7
| bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0]) print(bicycles[0].title())
print(bicycles[-1]) print(bicycles[-2])
|
3. 修改列表元素
1 2 3 4 5
| motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles)
motorcycles[0] = 'ducati' print(motorcycles)
|
4. 添加元素
1 2 3 4 5 6 7
| motorcycles.append('ducati') print(motorcycles)
motorcycles.insert(0, 'bmw') print(motorcycles)
|
5. 删除元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
del motorcycles[0] print(motorcycles)
motorcycles = ['honda', 'yamaha', 'suzuki'] popped = motorcycles.pop() print(popped) print(motorcycles)
first = motorcycles.pop(0) print(first)
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] motorcycles.remove('ducati') print(motorcycles)
|
官方文档:list.append()、list.pop()、list.remove()
6. 组织列表
永久排序 sort()
1 2 3 4 5 6
| cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars)
cars.sort(reverse=True) print(cars)
|
临时排序 sorted()
1 2 3
| cars = ['bmw', 'audi', 'toyota', 'subaru'] print(sorted(cars)) print(cars)
|
反转列表
1 2 3
| cars.reverse() print(cars) print(len(cars))
|
7. 避免索引错误
1 2 3 4 5 6 7 8 9 10 11
| motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[-1])
if motorcycles: print(motorcycles[0])
|
官方文档:Common Sequence Operations — 序列索引和切片操作规范。
📚 官方文档参考
🎓 AI 编程实战课程
程序员晚枫专注AI编程培训,通过 《30讲 · AI编程训练营》,让小白也能用AI做出实际项目。