【学习笔记】《Python编程 从入门到实践》第3章:Python列表完全指南——创建、修改、删除与排序

第3章 列表简介

本章目标:理解列表的概念,掌握创建、访问、修改、删除列表元素的方法,学会组织列表的常用操作。


3.1 列表是什么

列表 由一系列按特定顺序排列的元素组成。用方括号 [] 表示,逗号分隔元素。

python 复制代码
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
# ['trek', 'cannondale', 'redline', 'specialized']

建议给列表指定复数名称 ,如 lettersdigitsnames

3.1.1 访问列表元素

通过索引(从 0 开始)访问:

python 复制代码
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])                 # trek
print(bicycles[0].title())         # Trek(可对元素调用字符串方法)

3.1.2 索引从 0 而不是 1 开始

python 复制代码
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[1])     # cannondale(第二个元素)
print(bicycles[3])     # specialized(第四个元素)

# 负索引:-1 表示最后一个元素


`print(bicycles[-1])    # specialized`
`
print(bicycles[-2])    # redline(倒数第二个)`
`
print(bicycles[-3])    # cannondale`
`
`

3.1.3 使用列表中的各个值

python 复制代码
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
# My first bicycle was a Trek.

3.2 修改、添加和删除元素

3.2.1 修改列表元素

直接通过索引赋值:

python 复制代码
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles[0] = 'ducati'
print(motorcycles)
# ['ducati', 'yamaha', 'suzuki']

3.2.2 在列表中添加元素

append() --- 在末尾添加:

python 复制代码
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.append('ducati')
print(motorcycles)
# ['honda', 'yamaha', 'suzuki', 'ducati']

# 常用模式:先建空列表,再 append



motorcycles = []

motorcycles.append('honda')

motorcycles.append('yamaha')

motorcycles.append('suzuki')

print(motorcycles)


# ['honda', 'yamaha', 'suzuki']

insert() --- 在任意位置插入(指定索引和值):

python 复制代码
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
# ['ducati', 'honda', 'yamaha', 'suzuki']

insert(0, 'ducati') 在索引 0 处插入,原有元素右移。

3.2.3 从列表中删除元素

方法 用法 特点
del del list[index] 删除后无法再访问该值
pop() list.pop() 删除末尾元素并返回该值
pop(index) list.pop(index) 删除任意位置元素并返回
remove() list.remove(value) 按值删除第一个匹配项

del 语句 --- 按位置删除(不再需要该值):

python 复制代码
motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
print(motorcycles)
# ['yamaha', 'suzuki']

del motorcycles[1]

print(motorcycles)


# ['honda', 'suzuki']

pop() 方法 --- 删除并继续使用该值:

python 复制代码
# 默认弹出末尾
motorcycles = ['honda', 'yamaha', 'suzuki']
popped_motorcycle = motorcycles.pop()
print(motorcycles)           # ['honda', 'yamaha']
print(popped_motorcycle)     # suzuki

# 使用弹出的值


`last_owned = motorcycles.pop()`
`
print("The last motorcycle I owned was a " + last_owned.title() + ".")`
`
`

pop(index) --- 弹出任意位置:

python 复制代码
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
# The first motorcycle I owned was a Honda.

判断标准

  • 删除后不再使用del
  • 删除后还要使用pop()

remove() --- 按值删除(只删第一个匹配项):

python 复制代码
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
motorcycles.remove('ducati')
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']

# 可先用变量存储,删除后继续使用该值



too_expensive = 'ducati'

motorcycles.remove(too_expensive)

print("\nA " + too_expensive.title() + " is too expensive for me.")


# A Ducati is too expensive for me.

⚠️ remove() 只删除第一个匹配值。多个重复值需要用循环处理(第 7 章)。


3.3 组织列表

3.3.1 sort() --- 永久排序

python 复制代码
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# ['audi', 'bmw', 'subaru', 'toyota']

# 倒序排列



cars.sort(reverse=True)

print(cars)


# ['toyota', 'subaru', 'bmw', 'audi']

sort() 永久修改列表顺序,不可恢复。

3.3.2 sorted() --- 临时排序

python 复制代码
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")

print(sorted(cars))


print("\nHere is the original list again:")

print(cars)


# 倒序临时排序


`print(sorted(cars, reverse=True))`
`
`

sorted() 返回排序后的副本,不修改原列表。

3.3.3 reverse() --- 反转列表

python 复制代码
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
print(cars)
# ['subaru', 'toyota', 'audi', 'bmw']

reverse() 永久反转顺序,再次调用可恢复。

3.3.4 len() --- 获取列表长度

python 复制代码
>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)
4

3.4 使用列表时避免索引错误

IndexError: list index out of range --- 索引超出列表范围:

python 复制代码
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[3])    # ❌ IndexError(只有索引 0, 1, 2)

解决方法

  1. 尝试将索引减 1
  2. 使用 -1 访问最后一个元素(仅在列表非空时有效)
  3. 将列表或其长度打印出来,查看实际内容
python 复制代码
# 空列表使用 -1 也会出错
motorcycles = []
print(motorcycles[-1])   # ❌ IndexError

动手试一试

3-1 姓名

python 复制代码
names = ['Alice', 'Bob', 'Charlie']
print(names[0])
print(names[1])
print(names[2])

3-2 问候语

python 复制代码
names = ['Alice', 'Bob', 'Charlie']
print("Hello, " + names[0] + "!")
print("Hello, " + names[1] + "!")
print("Hello, " + names[2] + "!")

3-3 自己的列表

python 复制代码
commute = ['motorcycle', 'car', 'bike']
print("I would like to own a Honda " + commute[0] + ".")

3-4 ~ 3-7 嘉宾名单系列

python 复制代码
# 3-4 嘉宾名单
guests = ['Einstein', 'Mozart', 'Curie']
print("Dear " + guests[0] + ", please join me for dinner.")
print("Dear " + guests[1] + ", please join me for dinner.")
print("Dear " + guests[2] + ", please join me for dinner.")

# 3-5 修改嘉宾名单



print("\n" + guests[1] + " can't make it.")

guests[1] = 'Newton'

print("Dear " + guests[0] + ", please join me for dinner.")

print("Dear " + guests[1] + ", please join me for dinner.")

print("Dear " + guests[2] + ", please join me for dinner.")


# 3-6 添加嘉宾



print("\nI found a bigger table!")

guests.insert(0, 'Da Vinci')

guests.insert(2, 'Shakespeare')

guests.append('Tesla')

print("Dear " + guests[0] + ", please join me for dinner.")

print("Dear " + guests[1] + ", please join me for dinner.")

print("Dear " + guests[2] + ", please join me for dinner.")

print("Dear " + guests[3] + ", please join me for dinner.")

print("Dear " + guests[4] + ", please join me for dinner.")

print("Dear " + guests[5] + ", please join me for dinner.")


# 3-7 缩减名单


`print("\nSorry, I can only invite two people for dinner.")`
`
popped = guests.pop()`
`
print("Sorry " + popped + ", I can't invite you to dinner.")`
`
popped = guests.pop()`
`
print("Sorry " + popped + ", I can't invite you to dinner.")`
`
popped = guests.pop()`
`
print("Sorry " + popped + ", I can't invite you to dinner.")`
`
popped = guests.pop()`
`
print("Sorry " + popped + ", I can't invite you to dinner.")`
`
print("\nDear " + guests[0] + ", you're still invited.")`
`
print("Dear " + guests[1] + ", you're still invited.")`
`
del guests[0]`
`
del guests[0]`
`
print(guests)   # []`
`
`

3-8 放眼世界

python 复制代码
places = ['Tokyo', 'Iceland', 'New Zealand', 'Egypt', 'Brazil']
print(places)
print(sorted(places))
print(places)
print(sorted(places, reverse=True))
print(places)
places.reverse()
print(places)
places.reverse()
print(places)
places.sort()
print(places)
places.sort(reverse=True)
print(places)

3-9 晚餐嘉宾

python 复制代码
guests = ['Einstein', 'Mozart', 'Curie', 'Newton', 'Da Vinci']
print("I invited " + str(len(guests)) + " guests to dinner.")

3-10 尝试使用各个函数

python 复制代码
languages = ['Python', 'Java', 'C', 'JavaScript', 'Ruby']
print(languages)
print(sorted(languages))
languages.sort()
print(languages)
languages.sort(reverse=True)
print(languages)
languages.reverse()
print(languages)
print(len(languages))
languages.append('Go')
languages.insert(0, 'Swift')
print(languages)
languages.pop()
languages.remove('Swift')
print(languages)

3-11 有意引发错误

python 复制代码
items = [1, 2, 3]
# print(items[3])   # ❌ IndexError
print(items[-1])    # ✅ 使用 -1 安全访问最后一个

代码块汇总

python 复制代码
# 创建列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized']

# 访问元素(索引从 0 开始)



bicycles[0]           # 第一个元素

bicycles[-1]          # 最后一个元素


# 修改



motorcycles[0] = 'ducati'


# 添加



motorcycles.append('ducati')     # 末尾

motorcycles.insert(0, 'ducati')  # 指定位置


# 删除



del motorcycles[0]               # 按索引删除(不使用值)

popped = motorcycles.pop()       # 弹出末尾(使用值)

popped = motorcycles.pop(0)      # 弹出任意位置

motorcycles.remove('ducati')     # 按值删除(只删第一个)


# 排序



cars.sort()                      # 永久排序

cars.sort(reverse=True)          # 永久倒序

sorted(cars)                     # 临时排序

sorted(cars, reverse=True)       # 临时倒序


# 反转



cars.reverse()


# 长度


`len(cars)`
`
`

常见错误 / 陷阱

错误类型 说明 解决
IndexError 索引超出范围 索引从 0 开始,最大索引为 len(list) - 1
空列表 -1 空列表用 -1 也会出错 访问前检查列表是否为空
remove() 只删一个 重复值只删第一个 用循环处理
误用 sort() 以为 sort() 不影响原列表 sort() 永久修改,sorted() 临时修改

复习要点

  • 列表用 [] 表示,元素用逗号分隔
  • 索引从 0 开始,-1 访问最后一个
  • append() 末尾添加,insert() 任意位置插入
  • del / pop() / remove() 三种删除方式的区别和适用场景
  • sort() 永久排序 vs sorted() 临时排序
  • reverse() 反转列表顺序
  • len() 获取列表长度
  • 避免 IndexError:最大索引 = len(list) - 1

下一章,我们一起去操作操作列表<第4章-操作列表>

相关推荐
lunzi_fly7 小时前
【学习笔记】《Python编程 从入门到实践》第4章:for循环、range()、切片与元组
读书笔记·python 小白学习
lunzi_fly4 天前
【学习笔记】《Python编程 从入门到实践》第2章:变量命名规则、字符串操作与数值类型详解
读书笔记·python 小白学习
lunzi_fly8 天前
【学习笔记】《Python编程 从入门到实践》第1章学习笔记:Python环境搭建与Hello World(完整版)
读书笔记·python 小白学习