List: Store and Manage Multiple Items
Introduction
In this chapter, you will learn Python lists, one of the most frequently used data structures in real development. Lists let you store multiple values in order and update them when needed. Once you master lists, you can handle collections like user names, scores, products, and tasks efficiently.
Prerequisites
- Python
3.10+installed - Basic understanding of variables, strings, loops, and keywords
- Ability to run
.pyfiles in terminal or IDE
What Is a List
A list is an ordered, mutable collection of items.
Key points:
- Ordered: items keep their position
- Mutable: you can add, remove, and modify items
- Flexible: items can be different data types
# Create a basic list
fruits = ["apple", "banana", "orange"]
# Print the list
print(fruits)1) Create and Access List Items
Use square brackets [] to create lists and index positions to access items.
# Create list
colors = ["red", "green", "blue"]
# Access by index
print(colors[0]) # red
print(colors[2]) # blue
print(colors[-1]) # blueWarning
List indexing starts at 0.
Accessing an invalid index raises IndexError.
2) Modify List Items
Because lists are mutable, you can update elements directly.
# Original list
scores = [80, 75, 90]
# Update second item
scores[1] = 85
# Print updated list
print(scores) # [80, 85, 90]3) Add and Remove Items
Common list operations:
append()add one item to endinsert()add at specific positionremove()remove by valuepop()remove by index (or last item)
# Start list
tasks = ["read", "code"]
# Add new item to end
tasks.append("test")
# Insert item at index 1
tasks.insert(1, "review")
# Remove by value
tasks.remove("read")
# Remove and return last item
last_task = tasks.pop()
# Print final list and removed item
print(tasks)
print(last_task)4) Useful List Functions and Methods
Length
# Count list items
numbers = [10, 20, 30, 40]
print(len(numbers)) # 4Sort
# Sort list in ascending order
prices = [19, 5, 12, 7]
prices.sort()
print(prices) # [5, 7, 12, 19]Reverse
# Reverse current order
letters = ["a", "b", "c"]
letters.reverse()
print(letters) # ['c', 'b', 'a']Membership Check
# Check if item exists
users = ["tom", "amy", "leo"]
print("amy" in users) # TrueTip
Best Practice
Use descriptive list names like student_scores or shopping_cart so code reads like plain English.
5) Loop Through a List
Lists are often used with for loops.
# List of product names
products = ["mouse", "keyboard", "monitor"]
# Print each product
for product in products:
print(product)Loop with index and value:
# List with values
levels = ["beginner", "intermediate", "advanced"]
# Print index and value together
for idx, level in enumerate(levels):
print(idx, level)6) Real Mini Example: Shopping Cart Summary
This mini example uses list operations and looping for a practical task.
# Create shopping cart
cart = ["notebook", "pen", "usb drive"]
# Add one item
cart.append("headphones")
# Remove one item
cart.remove("pen")
# Print cart summary
print(f"Total items: {len(cart)}")
for item in cart:
print(f"- {item}")This pattern appears in e-commerce, to-do apps, and menu systems.
Common Beginner Mistakes
Mistake 1: Confusing append() and extend()
append() adds one item, while extend() adds items from another iterable.
Mistake 2: Removing Items While Looping Incorrectly
Directly removing items during iteration can skip elements unexpectedly.
Mistake 3: Assuming List Copy Is Independent
new_list = old_list points to the same list. Use old_list.copy() for a shallow copy.
Surprise Practice Challenge
Build a tiny "Top 3 Goals Tracker":
- Ask user to input 3 goals
- Store goals in a list
- Print them as numbered lines
- Ask which goal is completed
- Remove completed goal and print remaining goals
Reference implementation:
# Create empty goal list
goals = []
# Collect three goals
for i in range(1, 4):
goal = input(f"Enter goal #{i}: ").strip()
goals.append(goal)
# Print all goals
print("Your goals:")
for idx, goal in enumerate(goals, start=1):
print(f"{idx}. {goal}")
# Ask completed goal number
done_index = int(input("Which goal did you complete? (1-3): ")) - 1
# Remove completed goal if index is valid
if 0 <= done_index < len(goals):
removed_goal = goals.pop(done_index)
print(f"Great job! You completed: {removed_goal}")
else:
print("Invalid selection.")
# Print remaining goals
print("Remaining goals:")
for goal in goals:
print(f"- {goal}")FAQ
Can a list store mixed data types?
Yes. A list can contain strings, numbers, booleans, and even other lists.
What is the difference between pop() and remove()?
remove(value) deletes by value, while pop(index) deletes by position and returns the removed item.
How do I copy a list safely?
Use new_list = old_list.copy() or slicing new_list = old_list[:].
Should I always sort the original list?
Not always. If you need to keep original order, use sorted(list_name) to create a new sorted list.