List Basics

In previous lessons, variables could only hold one value. But in real life, data rarely comes as singletons — shopping carts have multiple items, leaderboards have multiple entries, articles have multiple paragraphs. Lists are designed to hold "a collection of data." They're Python's most flexible and commonly used data structure.


1. What Is a List

A list is defined with square brackets [], elements separated by commas. They can hold elements of different types:

PYTHON
# List of integers
numbers = [1, 2, 3, 4, 5]

# List of strings
fruits = ["apple", "banana", "orange"]

# Mixed types
mixed = [1, "hello", True, 3.14]

# Empty list
empty = []

print(numbers)   # [1, 2, 3, 4, 5]
print(fruits)    # ['apple', 'banana', 'orange']
print(empty)     # []
💡 Lists are ordered — elements maintain the order you add them, with fixed positions. Unlike sets, list elements can repeat.


2. Index Access

List indexing works exactly like strings — starts at 0, supports negative indices:

PYTHON
fruits = ["apple", "banana", "orange", "grape", "watermelon"]

# Positive: starts at 0
print(fruits[0])      # apple
print(fruits[2])      # orange
print(fruits[4])      # watermelon

# Negative: starts at -1 (last)
print(fruits[-1])     # watermelon
print(fruits[-2])     # grape
print(fruits[-5])     # apple

Accessing an out-of-range index causes an error:

PYTHON
# print(fruits[10])   # IndexError: list index out of range

Example: Get List Element Info (Difficulty ⭐)

PYTHON
# Given a student list
students = ["Alice", "Bob", "Charlie", "David", "Eve"]

# First and last
first = students[0]
last = students[-1]
print(f"First student: {first}")
print(f"Last student: {last}")

# First three
top3 = students[:3]           # Slice
print(f"Top 3: {top3}")

# List length
count = len(students)
print(f"Total students: {count}")
▶ Try it Yourself

3. List CRUD Operations

Lists are mutable — you can modify them in-place (unlike strings).

Adding Elements

PYTHON
# append() — add to the end
cities = ["Beijing", "Shanghai"]
cities.append("Guangzhou")
print(cities)               # ['Beijing', 'Shanghai', 'Guangzhou']

# insert() — insert at a specific position
cities.insert(1, "Shenzhen")
print(cities)               # ['Beijing', 'Shenzhen', 'Shanghai', 'Guangzhou']

# extend() — merge another list
more_cities = ["Hangzhou", "Chengdu"]
cities.extend(more_cities)
print(cities)               # ['Beijing', 'Shenzhen', 'Shanghai', 'Guangzhou', 'Hangzhou', 'Chengdu']

Removing Elements

PYTHON
# pop() — remove and return the element at a position (default last)
cities = ["Beijing", "Shanghai", "Guangzhou", "Shenzhen"]
last = cities.pop()         # Remove and return last
print(f"Removed: {last}")   # Shenzhen
print(cities)               # ['Beijing', 'Shanghai', 'Guangzhou']

first = cities.pop(0)       # Remove first
print(f"Removed: {first}")  # Beijing
print(cities)               # ['Shanghai', 'Guangzhou']

# remove() — remove the first matching value
cities = ["Beijing", "Shanghai", "Guangzhou", "Shanghai"]
cities.remove("Shanghai")   # Only removes the first "Shanghai"
print(cities)               # ['Beijing', 'Guangzhou', 'Shanghai']

# clear() — remove all elements
cities.clear()
print(cities)               # []

Modifying Elements

PYTHON
scores = [60, 70, 80, 90]
scores[2] = 85              # Change the third to 85
print(scores)               # [60, 70, 85, 90]

Finding Elements

PYTHON
# in — check if element exists
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)    # True
print("grape" in fruits)    # False

# index() — find position
print(fruits.index("banana")) # 1
# print(fruits.index("grape"))  # ValueError!
⚠️ Note: Using index() on a non-existent element raises an error. Use in first to check safely.

Example: Shopping Cart Management (Difficulty ⭐⭐)

PYTHON
# Simulate a shopping cart with a list
cart = []

# Add items
cart.append("apple")
cart.append("milk")
cart.append("bread")
cart.append("apple")         # Duplicates allowed
print(f"Cart: {cart}")

# Check quantity
print(f"Total items: {len(cart)}")

# Modify — change first apple to "apple (2-pack)"
cart[0] = "apple (2-pack)"
print(f"After update: {cart}")

# Remove last item
removed = cart.pop()
print(f"Removed: {removed}")
print(f"Final cart: {cart}")
▶ Try it Yourself

Output:

TEXT
Cart: ['apple', 'milk', 'bread', 'apple']
Total items: 4
After update: ['apple (2-pack)', 'milk', 'bread', 'apple']
Removed: apple
Final cart: ['apple (2-pack)', 'milk', 'bread']

4. Sorting and Reversing

PYTHON
numbers = [3, 1, 4, 1, 5, 9, 2]

# sort() — in-place sorting (modifies the original list)
numbers.sort()
print(numbers)              # [1, 1, 2, 3, 4, 5, 9]

# sort(reverse=True) — descending
numbers.sort(reverse=True)
print(numbers)              # [9, 5, 4, 3, 2, 1, 1]

# reverse() — reverse order
numbers.reverse()
print(numbers)              # [1, 1, 2, 3, 4, 5, 9]

# sorted() — returns a new list, doesn't modify the original
numbers = [3, 1, 4, 1, 5]
sorted_nums = sorted(numbers)
print(sorted_nums)          # [1, 1, 3, 4, 5]
print(numbers)              # [3, 1, 4, 1, 5] (unchanged)
💡 sort() vs sorted()? If you don't need the original order, use sort() (faster, more memory efficient). If you need to preserve the original order, use sorted().


5. List Slicing

Slicing works the same as with strings: list[start:end:step]

PYTHON
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(nums[2:6])            # [2, 3, 4, 5]
print(nums[:4])             # [0, 1, 2, 3] — first 4
print(nums[6:])             # [6, 7, 8, 9] — from 6 to end
print(nums[::2])            # [0, 2, 4, 6, 8] — every other
print(nums[::-1])           # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] — reversed

Slicing also supports assignment — a unique feature of lists:

PYTHON
nums = [0, 1, 2, 3, 4, 5]

# Replace a slice
nums[1:4] = [10, 20, 30]
print(nums)                 # [0, 10, 20, 30, 4, 5]

# Delete a slice
nums[1:4] = []
print(nums)                 # [0, 4, 5]

Example: Pagination with Slicing (Difficulty ⭐⭐)

PYTHON
# Paginated display — 3 items per page
items = ["Item A", "Item B", "Item C", "Item D", "Item E", "Item F", "Item G"]

page_size = 3
total_pages = (len(items) + page_size - 1) // page_size

for page in range(total_pages):
    start = page * page_size
    end = start + page_size
    page_items = items[start:end]
    print(f"Page {page + 1}: {page_items}")
▶ Try it Yourself

Output:

TEXT
Page 1: ['Item A', 'Item B', 'Item C']
Page 2: ['Item D', 'Item E', 'Item F']
Page 3: ['Item G']

6. Nested Lists

List elements can themselves be lists — this is called a nested list (or 2D list).

PYTHON
# 3x4 "matrix"
matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

# Access: first row, then column
print(matrix[0])        # [1, 2, 3, 4] — first row
print(matrix[1][2])     # 7 — second row, third column
print(matrix[2][0])     # 9 — third row, first column

Example: Student Score Table (Difficulty ⭐⭐⭐)

PYTHON
# Store student scores in a nested list
# Each row: [name, Chinese, Math, English]
scores = [
    ["Alice", 85, 92, 78],
    ["Bob", 90, 88, 95],
    ["Charlie", 76, 85, 82],
]

# Calculate and output each student's average
for student in scores:
    name = student[0]
    avg = (student[1] + student[2] + student[3]) / 3
    print(f"{name}: Average {avg:.1f}")

# Output all math scores
print("Math scores:")
for student in scores:
    print(f"  {student[0]}: {student[1]}")
▶ Try it Yourself

Output:

TEXT
Alice: Average 85.0
Bob: Average 91.0
Charlie: Average 81.0
Math scores:
  Alice: 85
  Bob: 90
  Charlie: 76

Common Use Cases


❓ FAQ

Q What's the difference between lists and strings?
A The main difference is lists are mutable (can be modified), while strings are immutable (can't change the original). Lists can hold different data types; strings can only hold characters. Similarities: both support indexing, slicing, len(), and in operations. ⚠️ Q: What's the difference between append() and extend()? A: append() adds the entire argument as a single element — if you pass a list, it becomes a nested list. extend() adds each element from the argument individually. a = [1,2]; a.append([3,4]) gives [1,2,[3,4]], while a.extend([3,4]) gives [1,2,3,4]. Q: What happens if I try to remove() a non-existent element? A: It raises a ValueError. So check with in first: if "xxx" in my_list: my_list.remove("xxx"). Or use a list comprehension to create a new filtered list: new_list = [x for x in my_list if x != "xxx"] (we'll learn this in the next lesson).

📖 Summary

  • Lists use [], ordered, mutable, allow duplicates, can hold different types
  • Indexing starts at 0, supports negative indices; slicing works like strings
  • Add: append() at end, insert() at position, extend() to merge
  • Remove: pop() returns removed, remove() by value, clear() all
  • Modify: list[index] = new_value
  • Check: in for existence, index() for position
  • Sort: sort() in-place, sorted() returns new list
  • Nested lists enable 2D data structures, accessed via list[row][col]

📝 Exercises

  1. Basic (Difficulty ⭐): Create a list of 5 movies you like. Use append() to add a new one, pop() to remove the last, sort() alphabetically, then output the list length.

  2. Intermediate (Difficulty ⭐⭐): Given numbers = [23, 45, 12, 67, 34, 89, 5, 18], find and output the max, min, sum, and average. Hint: Use built-in functions like max(), min(), sum(), len().

  3. Challenge (Difficulty ⭐⭐⭐): Write a "To-Do List Manager." Use a list to store tasks. Support: add:Buy milk, done:2 (remove by number), list (show all). Use while True to continuously accept commands; exit to quit. Hint: Use split(":") to parse commands.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏