课程 · 12 · 05 / 12
Lists: Your First Data Structure
Explore Python lists for storing collections of data. Learn indexing, slicing, and essential list methods.
TIPLearning Objectives: After this lesson, you'll master Python lists for storing collections of data, understand indexing and slicing, and learn essential list methods for data manipulation.
What are Lists? The Train Analogy
Before diving into code, let's understand lists through a powerful analogy:
Lists are like trains - a series of connected cars carrying cargo.
Imagine a freight train traveling across the country:
🚂 The List Train
- The train: Your Python list
- Train cars: Individual items/elements in the list
- Car numbers: Indices (0, 1, 2, 3...)
- Cargo in each car: The actual data (numbers, strings, objects)
- The engine: Python managing the list for you
Key Properties of the Train (List):
- Ordered: Cars stay in sequence (just like list items maintain order)
- Numbered: Each car has a position number starting from 0
- Flexible cargo: Each car can carry different types of cargo
- Changeable: Can add cars, remove cars, rearrange cargo
- Accessible: Can access any car directly by its number
🚂 List Train: colors = ["red", "green", "blue", "yellow"] Car 0 Car 1 Car 2 Car 3 ┌─────────┬─────────┬─────────┬─────────┐ │ "red" │ "green" │ "blue" │"yellow" │ └─────────┴─────────┴─────────┴─────────┘ Index: 0 1 2 3 Negative: -4 -3 -2 -1
Train Operations = List Operations:
- Add a car:
colors.append("purple")- attach new car at end - Insert a car:
colors.insert(1, "orange")- couple car at specific position - Remove a car:
colors.remove("green")- detach and remove specific car - Check a car:
colors[2]- inspect cargo in car #2 - Count cars:
len(colors)- how many cars in the train?
What are Lists?
A list is Python's most versatile data structure - an ordered collection that can store multiple items of any type. Think of it as a container with numbered slots, where each slot can hold any Python value.
List Indexing
Each item in a list has an index (position number). Python uses zero-based indexing:
List Slicing
Slicing lets you extract portions of a list using the syntax list[start:end:step]:
Essential List Methods
Lists come with many built-in methods for manipulation:
List Operations and Functions
Interactive List Visualization
Let's see how list operations work visually:
List Comprehensions (Preview)
A powerful Python feature for creating lists:
Working with Lists of Different Types
Common List Patterns
Practical Examples
Example 1: Grade Tracker
Example 2: Shopping Cart
Practice Exercises
Exercise 1: List Manipulation
Exercise 2: Word List Processor
Key Takeaways
✅ Lists are ordered collections - Items have specific positions (indices)
✅ Zero-based indexing - First item is at index 0, last at index -1
✅ Slicing syntax - list[start:end:step] extracts portions
✅ Mutable - Lists can be modified after creation
✅ Essential methods - append(), insert(), remove(), pop(), sort()
✅ List comprehensions - Concise way to create and filter lists
✅ Versatile - Can store any type of data, including other lists
Next Steps
In the next lesson, we'll explore dictionaries and sets - data structures that excel at storing key-value pairs and unique collections respectively.
Ready to learn about Python's most powerful data structures? The next lesson will introduce dictionaries and sets!
Further Reading
Visualize It
- Python Tutor — paste any list code and watch how
b = ashares a reference butb = a[:]creates a copy. The arrows make it instantly clear. - VisuAlgo — Sorting Algorithms — animated visualization of what
list.sort()actually does under the hood (Timsort).
Official Docs
- Python Tutorial — Data Structures — official walkthrough of lists, list methods, and comprehensions.
- Python — Sequence Types — full method reference for
list,tuple,range. - Time Complexity Wiki — Python — Big-O cheat sheet for every list operation. Bookmark this.
Tutorials
- Real Python — Python Lists and Tuples — the canonical reference walkthrough.
- Real Python — Sorting in Python — covers
sorted()vs.sort(),key=,reverse=, and stability. - Trey Hunner — How to make a flat list out of a list of lists — the Stack Overflow answer with 5,000 upvotes; worth memorizing.
Performance & Modernization
- Use
bisectfor sorted-list operations —O(log n)insert + lookup when order matters. collections.deque— when you need fastpopleft()(lists areO(n)for that).- Book: Fluent Python — Chapter 2 ("Sequences") and Chapter 12 ("Special Methods for Sequences").