Use list and tuple

Python is an entry-friendly programming language, and container type (a structure that can hold multiple data) is the first lesson that cannot be avoided. list (list) and tuple (tuple) are the most commonly used "ordered sequence dual containers" - they can store any type of elements, and both support index slicing, but one "changes it if you want", and the other "once created, it cannot be moved (the structure is not allowed to be moved, the content depends on the element)". Today I will explain all the usage, differences and best practices of these two~


List

List is the most basic variable ordered sequence in Python, which is suitable for storing data that needs to be dynamically added, deleted, and modified.

Create a list

Square brackets for lists[]Wrap elements separated by commas:

# 1. 创建同类型的字符串列表
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates)  # 输出: ['Michael', 'Bob', 'Tracy']

# 2. 创建混合类型的列表(Python灵活但不推荐,尽量保持同类型提升效率)
mixed_list = ['Apple', 123, True, 3.14]
print(mixed_list)

# 3. 创建空列表
empty_list = []
print(empty_list)  # 输出: []

Access list elements

There are two core rules for using index (subscript) to locate elements:

⚠️ Attention! Newbies often fall into pitfalls:

  1. Index always starts from 0 (not 1);
  2. Negative indexes work backwards from -1 (the last element), for example -2 is the second to last element;
  3. Index out of bounds will be thrown directlyIndexError: list index out of range
print(classmates[0])   # 输出: 'Michael' (第一个元素)
print(classmates[-1])  # 输出: 'Tracy' (最后一个元素)

# 索引越界会报错
# print(classmates[3])  # IndexError

List common operations

1. Get the length of the list

Using Python’s built-in universal length functionlen()

print(len(classmates))  # 输出: 3

2. Modify elements

Just assign the value directly through the index:

classmates[1] = 'Sarah'
print(classmates)  # 输出: ['Michael', 'Sarah', 'Tracy']

3. Add elements

There are three common methods, each with its own applicable scenarios:

# 方法1:append() —— 末尾追加单个元素,效率O(1)!大列表优先用
classmates.append('Adam')
print(classmates)  # 输出: ['Michael', 'Sarah', 'Tracy', 'Adam']

# 方法2:insert(i, x) —— 指定位置i插入元素x,效率O(n)(后面元素要后移)
classmates.insert(1, 'Jack')
print(classmates)  # 输出: ['Michael', 'Jack', 'Sarah', 'Tracy', 'Adam']

# 方法3:extend(iterable) —— 一次性追加多个元素,循环append的替代方案
classmates.extend(['Lily', 'Lucy'])
print(classmates)  # 输出调整后的完整列表

4. Delete elements

Three common methods:

# 方法1:pop() —— 不传索引删末尾(和append配对,效率O(1)),传索引删指定位置,返回被删元素
last = classmates.pop()
print(last)        # 输出: 'Lucy'
print(classmates)  # 输出少了Lucy的列表

second = classmates.pop(1)
print(second)      # 输出: 'Jack'

# 方法2:remove(x) —— 删除**第一个匹配的值**x,值不存在会抛ValueError
classmates.remove('Sarah')
print(classmates)  # 输出调整后的列表

# 方法3:del 语句 —— 直接删除指定位置/切片,无返回值
del classmates[1]  # 删除索引1的元素
print(classmates)

Multidimensional lists (nested lists)

Lists can be nested within lists to form two-dimensional/three-dimensional data structures (such as simulation matrices and grids):

# 模拟3x3的二维矩阵
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(matrix[1][1])  # 输出: 5(第二行第二列,索引从0开始)

# 混合嵌套(不推荐同层混合类型)
nested_list = ['python', 'java', ['asp', 'php'], 'scheme']
print(nested_list[2][1])  # 输出: 'php'

💡 Practical tips: Want to quickly get a column of a two-dimensional list? availablezip(*matrix)Transpose first (the result is an iterator of the tuple, and to convert it into a list, addlist()), we will learn more about iterators later~


List slicing (super useful function!)

Slicing can access a subset of the list at once. The complete syntax islist[start:end:step], all three parameters are optional**!

  • start: Starting index (default 0, inclusive)
  • end:End index (default to the end, not included)
  • step: step size (default 1, negative number means reverse direction)
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 1. 基本切片
print(numbers[2:5])   # 输出: [2, 3, 4]
print(numbers[:3])    # 输出: [0, 1, 2](从头开始)
print(numbers[5:])    # 输出: [5, 6, 7, 8, 9](到末尾结束)
print(numbers[:])     # 输出完整列表(相当于浅拷贝)

# 2. 步长切片
print(numbers[::2])   # 输出: [0, 2, 4, 6, 8](隔一个取一个)
print(numbers[1::2])  # 输出: [1, 3, 5, 7, 9]

# 3. 反向切片(一行代码反转列表!Pythonic写法)
print(numbers[::-1])  # 输出: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Tuple

Tuples are pseudo-immutable ordered sequences in Python, suitable for storing fixed data that should not be modified.

Create tuple

Tuples with parentheses()Wrapping elements (sometimes can be omitted, such as function return, tuple unpacking), but there is a super important rule:

⚠️ **Super warning! ** Create a tuple with only one element, must add a comma! Otherwise, Python will treat it as an ordinary bracket operator (priority control), creating a variable with a single value!

# 1. 创建多元素元组
classmates = ('Michael', 'Bob', 'Tracy')
print(classmates)  # 输出: ('Michael', 'Bob', 'Tracy')

# 2. 创建单个元素的元组(必须加逗号!)
single_tuple = (1,)
print(single_tuple)       # 输出: (1,)
print(type(single_tuple)) # <class 'tuple'>

# 3. 不加逗号的错误示范
not_a_tuple = (1)
print(not_a_tuple)       # 输出: 1(整数)
print(type(not_a_tuple)) # <class 'int'>

# 4. 创建空元组
empty_tuple = ()
print(empty_tuple)  # 输出: ()

Access tuple elements

It is exactly the same as a list - both indexing and slicing can be used! But because it is immutable, elements cannot be modified, added or deleted:

print(classmates[0])   # 输出: 'Michael'
print(classmates[-1])  # 输出: 'Tracy'

# 尝试修改会报错
# classmates[0] = 'Adam'  # TypeError: 'tuple' object does not support item assignment

The "pseudo-immutability" trap of tuples

The immutability of tuples refers to the immutability of the "reference address" of each element in the tuple**! If the element itself is a mutable object (such as list, dict, set), we can modify the content of this mutable object! This is a pitfall that novices often step into:

mixed_tuple = ('a', 'b', ['A', 'B'])
# ✅ 可以修改内部可变对象的内容
mixed_tuple[2][0] = 'X'
print(mixed_tuple)  # 输出: ('a', 'b', ['X', 'B'])

# ❌ 不能替换整个可变对象的引用
# mixed_tuple[2] = ['C', 'D']  # TypeError

Tuple Unpacking - the core operation of Pythonic!

Tuple unpacking can assign the elements of the tuple to multiple variables at one time, which is super practical!

# 1. 基本坐标赋值
point = (3, 4)
x, y = point
print(x, y)  # 输出: 3 4

# 2. 函数返回多值(Python函数返回多值的本质就是返回元组!)
def get_size(file_path):
    # 假设这里读取了文件宽高
    return 1024, 2048  # 等价于 return (1024, 2048)
width, height = get_size("test.txt")
print(f"文件宽:{width}px,高:{height}px")

# 3. 快速交换变量(不用临时变量temp!)
a, b = 1, 2
a, b = b, a
print(f"交换后:a={a}, b={b}")

# 4. 遍历字典的键值对(items()返回的是键值对元组的迭代器)
user = {"name": "Alice", "age": 20}
for k, v in user.items():
    print(f"{k}: {v}")

List vs Tuple: Core Comparison Cheat Sheet

PropertiesListTuple
Syntax symbolsSquare brackets[]parentheses()(sometimes can be omitted)
VariabilityFully mutable: supports addition, deletion and modification of elementsPseudo-immutable: element references are immutable, and the content of variable elements can be changed
PerformanceSlightly slower: no cache optimization for construction and traversalFaster: Python caches small immutable objects and takes up less memory
Common methodsappend()/insert()/extend() pop()/remove() sort()/reverse()etc.Rarely: Onlycount(x)(count the number of occurrences) andindex(x)(find first location)
Best Applicable Scenarios1. Dynamic data container (to-do list, array to be sorted)
2. Data that needs to be added, deleted, or modified
1. Constant/fixed configuration (coordinates, RGB colors)
2. Function returns multiple values
3. Dictionary keys (must be immutable objects)
4. Enumeration value alternatives

A small test of skills (practice questions)

L = [
    ['Apple', 'Google', 'Microsoft'],
    ['Java', 'Python', 'Ruby', 'PHP'],
    ['Adam', 'Bart', 'Bob']
]

# 1. 打印指定元素
print(L[0][0])  # Apple
print(L[1][1])  # Python
print(L[2][2])  # Bob

# 2. 判断变量类型(用type()验证更直观)
check_vars = [(), (1), [2], (3,), (4,5,6)]
for var in check_vars:
    print(f"{var} 的类型是:{type(var).__name__}")

Expected output:

Apple
Python
Bob
() 的类型是:tuple
1 的类型是:int
[2] 的类型是:list
(3,) 的类型是:tuple
(4, 5, 6) 的类型是:tuple

Core points & scene shorthand

  1. Ordered sequence dual containers: Both list and tuple support common operations such as indexing, slicing, len(), and iteration;
  2. The core difference lies in “change”:
    • List:[], variable, flexible priority;
    • Tuple:()(Add a comma to a single element!), pseudo-immutable, performance/security priority;
  3. Pitfall reminder: The content of variable elements in Tuple can be changed, but the reference cannot be changed;
  4. Must learn tuple unpacking: This is one of the cores of Python code simplicity.

Mastering lists and tuples is the first step in Python programming. They will be everywhere in the subsequent learning of loops, functions, and dictionaries. Write a few more practice questions and you will be able to master them soon!