Skip to content

Python 列表

工作使用列表: indexing, slicing, 方法, 排序, and 列表 comprehensions for 有序集合.

你将学到

  • 创建, 索引, and slice 列表
  • 添加 and 移除元素使用 append, insert, pop, 移除
  • 排序 and reverse 列表 in 位置 and 使用排序()
  • Use 列表 comprehensions for concise transformations
  • 复制列表 and avoid shared-引用 bugs

概念讲解

Creating Lists

list 是一种 ordered, mutable collection that can hold any type of object. Lists are Python's most versatile data structure:

empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
nested = [[1, 2], [3, 4], [5, 6]]

Lists can hold mixed types and be nested to any depth. They are the go-to structure whenever you need an ordered, changeable sequence.

Indexing and Slicing

Lists support the same indexing and slicing syntax as strings:

fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0])     # apple
print(fruits[-1])    # date
print(fruits[1:3])   # ['banana', 'cherry']
print(fruits[::-1])  # reversed list

Slicing a list always returns a new list — the original is unchanged.

Adding and Removing Elements

fruits = ["apple", "banana"]

# Adding
fruits.append("cherry")          # add to end
fruits.insert(0, "apricot")      # insert at index 0
fruits.extend(["date", "fig"])   # add multiple

# Removing
fruits.pop()                     # remove and return last
fruits.pop(0)                    # remove and return index 0
fruits.remove("banana")          # remove first match by value
  • .append() adds one element to the end — the most common list operation
  • .extend() adds all elements from another iterable
  • .pop() removes by index (default: last) and returns the value
  • .移除() removes by value (first match only)

Sorting

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()              # in-place: [1, 1, 2, 3, 4, 5, 6, 9]
numbers.sort(reverse=True)  # descending

# sorted() returns a new list — original unchanged
original = [3, 1, 4]
ordered = sorted(original)

# Sort by a key function
words = ["banana", "apple", "cherry"]
words.sort(key=len)         # sort by length

Use .排序() when you want to modify the list in place, and 排序() when you want a new sorted list without changing the original. The 键 parameter lets you sort by any function.

List Comprehensions

A concise way to create lists from existing iterables:

squares = [x ** 2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
pairs = [(x, y) for x in range(3) for y in range(3)]

List comprehensions are both faster and more readable than equivalent for-loops with .append(). They are a hallmark of idiomatic Python.

Copying Lists

Because variables are references, b = does not copy a list — both point to the same object:

a = [1, 2, 3]
b = a              # same object!
b.append(4)
print(a)           # [1, 2, 3, 4] — a changed too

# To copy:
shallow = a.copy()        # or list(a), or a[:]
import copy
deep = copy.deepcopy(a)   # for nested lists

Use .复制() for a shallow copy (one level) and 复制.deepcopy() for nested structures.

示例代码

              # Creating and indexing
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0])      # apple
print(fruits[-1])     # date
print(fruits[1:3])    # ['banana', 'cherry']

# Adding and removing
fruits.append("fig")
fruits.insert(0, "apricot")
print(fruits)         # ['apricot', 'apple', 'banana', 'cherry', 'date', 'fig']

removed = fruits.pop()     # removes 'fig'
fruits.remove("banana")    # removes by value
print(fruits)

# Sorting
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers)        # [1, 1, 2, 3, 4, 5, 6, 9]

words = ["banana", "apple", "cherry"]
words.sort(key=len)
print(words)          # ['apple', 'banana', 'cherry'] (by length)

# List comprehension
squares = [x ** 2 for x in range(5)]
print(squares)        # [0, 1, 4, 9, 16]

evens = [x for x in range(20) if x % 2 == 0]
print(evens)

# Copying — avoid shared reference
original = [1, 2, 3]
copy = original.copy()
copy.append(4)
print(original)       # [1, 2, 3] — unchanged
            

Shows 列表 creation, indexing/slicing, append/insert/pop/移除, in-位置排序使用键 函数, 列表 comprehensions for 筛选 and 映射, and 复制() 方法到 avoid shared-引用 bugs.

动手试一试

  • JSON Formatter

    列表 serialize directly 到 JSON 数组 — 格式 and inspect 它们.

  • 文本计数器

    拆分文本到 列表的 words 是常见列表操作.

常见错误

错误写法

Using b = and expecting independent 复制的 列表

正确做法

b = 创建引用到 相同列表对象. Use b = .复制(), b = 列表(), or b = [:] for shallow 复制. For nested 列表, use 复制.deepcopy().

错误写法

移除元素虽然 iterating over 相同列表

正确做法

修改列表虽然 iterating over 它 skips 元素 and causes bugs. Iterate over 复制 (for x in lst[:]:) or 构建新 列表使用 comprehension 相反.

相关速查表

练习 Python 列表

14 个练习

练习 Python 列表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误