Lesson 2 • Intermediate
Lists in Python
Store and manage multiple values in a single variable using Python lists.
What You'll Learn in This Lesson
- ✓What a list is and why it's Python's most-used data structure
- ✓How to access items by index (including negative indexing)
- ✓How to add, remove, and change items in a list
- ✓How to slice lists to extract subsets
- ✓How to loop through lists and search for items
- ✓Useful list methods: sort, reverse, count, len
1. What Are Lists?
A list is a collection that stores multiple items in a single variable. Lists are ordered, changeable, and allow duplicate values.
Key Characteristics
- Ordered — Items have a defined order (index 0, 1, 2...)
- Mutable — You can add, remove, or change items
- Allow duplicates — Same value can appear multiple times
- Mixed types — Can hold strings, numbers, booleans, etc.
2. Creating Lists
| Type | Example | Description |
|---|---|---|
| Empty list | my_list = [] | Start with nothing |
| Strings | ["a", "b", "c"] | List of text values |
| Numbers | [1, 2, 3, 4, 5] | List of integers |
| Mixed | [1, "hello", True] | Different types together |
| Nested | [[1, 2], [3, 4]] | Lists inside lists |
Try It: Creating Lists
Different ways to create lists
# Different ways to create lists
# Empty list
my_list = []
print("Empty:", my_list)
# List with strings
fruits = ["apple", "banana", "cherry"]
print("Fruits:", fruits)
# List with numbers
numbers = [10, 20, 30, 40, 50]
print("Numbers:", numbers)
# Mixed types
mixed = [1, "hello", True, 3.14]
print("Mixed:", mixed)
# How many items?
print(f"Fruits has {len(fruits)} items")3. Accessing Items by Index
Each item in a list has an index (position number). Python uses zero-based indexing — the first item is at index 0.
| Code | Result | Explanation |
|---|---|---|
| fruits[0] | "apple" | First item |
| fruits[2] | "cherry" | Third item |
| fruits[-1] | "date" | Last item (negative index) |
| fruits[-2] | "cherry" | Second to last |
Try It: Accessing Items
Use indexes to access list items
fruits = ["apple", "banana", "cherry", "date"]
# Positive indexing (from start)
print("First item:", fruits[0])
print("Second item:", fruits[1])
print("Third item:", fruits[2])
# Negative indexing (from end)
print("Last item:", fruits[-1])
print("Second to last:", fruits[-2])
# Get length of list
print(f"Total items: {len(fruits)}")IndexError. Always check with len() if unsure.4. Changing List Items
Lists are mutable — you can change items after creation by assigning a new value to a specific index.
Try It: Changing Items
Modify items in a list
colors = ["red", "green", "blue"]
print("Original:", colors)
# Change single item
colors[0] = "yellow"
print("After change:", colors)
# Change last item
colors[-1] = "purple"
print("After another change:", colors)5. Adding Items to Lists
| Method | What It Does | Example |
|---|---|---|
| .append(item) | Add item to the end | fruits.append("mango") |
| .insert(i, item) | Add item at position i | fruits.insert(1, "pear") |
| .extend(list) | Add all items from another list | fruits.extend(["kiwi", "lime"]) |
Try It: Adding Items
Add items with append, insert, and extend
fruits = ["apple", "banana"]
print("Start:", fruits)
# append - add to end
fruits.append("cherry")
print("After append:", fruits)
# insert - add at specific position
fruits.insert(1, "blueberry")
print("After insert at 1:", fruits)
# extend - add multiple items
fruits.extend(["date", "elderberry"])
print("After extend:", fruits)6. Removing Items from Lists
| Method | What It Does | Example |
|---|---|---|
| .remove(item) | Remove first match by value | fruits.remove("banana") |
| .pop() | Remove and return last item | last = fruits.pop() |
| .pop(i) | Remove and return item at index i | first = fruits.pop(0) |
| .clear() | Remove all items | fruits.clear() |
| del list[i] | Delete item at index i | del fruits[0] |
Try It: Removing Items
Remove items with remove, pop, and del
fruits = ["apple", "banana", "cherry", "banana", "date"]
print("Start:", fruits)
# remove - by value (first occurrence only)
fruits.remove("banana")
print("After remove banana:", fruits)
# pop - remove and return last item
last = fruits.pop()
print(f"Popped: {last}, Remaining:", fruits)
# pop(0) - remove first item
first = fruits.pop(0)
print(f"Popped first: {first}, Remaining:", fruits).remove() raises a ValueError if the item is not in the list. Check first with if item in list:7. List Slicing — Get a Range of Items
Slicing lets you get a portion of a list using the syntaxlist[start:end].
| Code | Result | Meaning |
|---|---|---|
| nums[1:4] | [1, 2, 3] | Index 1 to 3 (4 excluded) |
| nums[:3] | [0, 1, 2] | First 3 items |
| nums[3:] | [3, 4, 5] | From index 3 to end |
| nums[-2:] | [4, 5] | Last 2 items |
| nums[::2] | [0, 2, 4] | Every 2nd item |
| nums[::-1] | [5, 4, 3, 2, 1, 0] | Reversed list |
Try It: List Slicing
Extract portions of a list
nums = [0, 1, 2, 3, 4, 5]
print("Original:", nums)
# Get a range
print("nums[1:4]:", nums[1:4]) # [1, 2, 3]
# From start / to end
print("nums[:3]:", nums[:3]) # [0, 1, 2]
print("nums[3:]:", nums[3:]) # [3, 4, 5]
# Negative slicing
print("Last 2:", nums[-2:]) # [4, 5]
# With step
print("Every 2nd:", nums[::2]) # [0, 2, 4]
print("Reversed:", nums[::-1]) # [5, 4, 3, 2, 1, 0]8. Looping Through Lists
Use a for loop to go through each item:
| Method | Use When | Example |
|---|---|---|
| for item in list: | You just need the items | for fruit in fruits: |
| for i, item in enumerate(list): | You need index + item | for i, fruit in enumerate(fruits): |
Try It: Looping Through Lists
Iterate over list items
fruits = ["apple", "banana", "cherry"]
# Simple loop - just items
print("Simple loop:")
for fruit in fruits:
print(fruit)
# With index using enumerate
print("\nWith index:")
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Start counting from 1 instead of 0
print("\nNumbered list:")
for num, fruit in enumerate(fruits, start=1):
print(f"{num}. {fruit}")9. Useful List Methods
| Method/Function | What It Does | Returns |
|---|---|---|
| len(list) | Number of items | Integer |
| .sort() | Sort ascending (modifies list) | None |
| .sort(reverse=True) | Sort descending | None |
| .reverse() | Reverse the order | None |
| .count(x) | Count occurrences of x | Integer |
| .index(x) | Find position of x | Integer |
| .copy() | Create a copy | New list |
| sum(list) | Sum of numbers | Number |
| min(list) / max(list) | Smallest / largest value | Item |
Try It: List Methods
Common list operations
numbers = [5, 2, 8, 1, 9, 2, 5]
print("Original:", numbers)
# Sorting
numbers.sort()
print("Sorted:", numbers)
numbers.sort(reverse=True)
print("Descending:", numbers)
# Counting
print(f"Count of 5: {numbers.count(5)}")
# With number lists
nums = [10, 20, 30, 40]
print(f"Sum: {sum(nums)}")
print(f"Min: {min(nums)}, Max: {max(nums)}")
print(f"Average: {sum(nums) / len(nums)}")10. Checking if Item Exists
Use in andnot in to check membership:
Try It: Membership Check
Check if items exist in a list
fruits = ["apple", "banana", "cherry"]
# Check if item exists
if "banana" in fruits:
print("Yes, banana is in the list!")
if "grape" not in fruits:
print("No, grape is NOT in the list")
# Practical use: safe removal
item_to_remove = "orange"
if item_to_remove in fruits:
fruits.remove(item_to_remove)
else:
print(f"{item_to_remove} not found in list")11. List Comprehension (Advanced)
List comprehension is a concise way to create lists in one line. It is more advanced but very powerful once you learn it.
squares = []
for x in range(5):
squares.append(x ** 2)
# [0, 1, 4, 9, 16]squares = [x ** 2 for x in range(5)] # [0, 1, 4, 9, 16]
Try It: List Comprehension
Create lists with one-line expressions
# Basic list comprehension
squares = [x ** 2 for x in range(6)]
print("Squares:", squares)
# With condition - only even numbers
evens = [x for x in range(10) if x % 2 == 0]
print("Evens:", evens)
# Transform items
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print("Uppercase:", upper_words)
# Get lengths
lengths = [len(word) for word in words]
print("Lengths:", lengths)12. Common Mistakes to Avoid
| Mistake | Problem | Solution |
|---|---|---|
| Index out of range | list[10] | Check len(list) first |
| Forgetting 0-indexing | Expecting first item at 1 | First item is at index 0 |
| Removing nonexistent item | .remove("x") | Check if x in list: first |
| Aliasing instead of copying | list2 = list1 | Use list2 = list1.copy() |
| Using parentheses | (1, 2, 3) | Use square brackets [1, 2, 3] |
13. Practical Examples
Example 1: Shopping Cart
Shopping Cart
Build a simple shopping cart
# Simple shopping cart
cart = []
# Add items
cart.append("Milk")
cart.append("Eggs")
cart.append("Bread")
print("Cart:", cart)
# Remove an item
cart.remove("Milk")
print("After removing Milk:", cart)
# Check if item in cart
if "Eggs" in cart:
print("Don't forget the eggs!")Example 2: Grade Calculator
Grade Calculator
Calculate statistics from grades
# Calculate average grade
grades = [85, 90, 78, 92, 88]
average = sum(grades) / len(grades)
highest = max(grades)
lowest = min(grades)
print(f"Grades: {grades}")
print(f"Average: {average:.1f}")
print(f"Highest: {highest}")
print(f"Lowest: {lowest}")Example 3: To-Do List
To-Do List
Manage tasks with a list
# Simple to-do list
todos = ["Buy groceries", "Clean room", "Study Python"]
print("My To-Do List:")
for i, task in enumerate(todos, start=1):
print(f"{i}. {task}")
# Mark first task as done (remove it)
completed = todos.pop(0)
print(f"\nCompleted: {completed}")
# Add new task
todos.append("Walk the dog")
print("\nUpdated To-Do List:")
for i, task in enumerate(todos, start=1):
print(f"{i}. {task}")Summary: Quick Reference
| Operation | Syntax | Example |
|---|---|---|
| Create | [item1, item2] | fruits = ["apple", "banana"] |
| Access | list[index] | fruits[0] |
| Change | list[i] = new | fruits[0] = "apricot" |
| Add | .append(item) | fruits.append("cherry") |
| Remove | .remove(item) | fruits.remove("banana") |
| Slice | list[start:end] | fruits[1:3] |
| Length | len(list) | len(fruits) |
| Loop | for item in list: | for fruit in fruits: |
| Check exists | item in list | "apple" in fruits |
Lesson 7 complete — you've unlocked Python's most-used data structure!
Lists are everywhere in Python — shopping carts, user records, game inventories, search results. You can now create, access, modify, slice, sort, and loop through them.
🚀 Up next: Dictionaries — store data with named keys instead of position numbers, perfect for structured records like user profiles.
Sign up for free to track which lessons you've completed and get learning reminders.