← Previous

Lesson 5

Lists and list methods

~35 min

1. Core Collections: Lists, Tuples, and Sets

As you build larger programs, storing single pieces of data in individual variables becomes impractical. Python provides powerful built-in collection types to group multiple values together. The three primary sequential collections are:

  • Lists ([val1, val2]): Ordered, mutable (changeable) sequences. Items can be added, updated, or removed. Duplicates are allowed.
  • Tuples ((val1, val2)): Ordered, immutable (unchangeable) sequences. Once defined, they cannot be modified. They are faster than lists and serve as read-only templates.
  • Sets ({val1, val2}): Unordered, unindexed collections. They only store unique elements (any duplicates are automatically filtered out).

2. Indexing and Slicing Sequences

Lists and tuples support indexing and slicing. Python indexes start at 0. Negative indexes count backward from the end (e.g., -1 is the last item). Slicing extracts a sub-sequence using the syntax list[start:stop] (where stop is exclusive).

fruits = ["apple", "banana", "cherry", "date"]

print(fruits[0])      # Prints: "apple" (first element)
print(fruits[-1])     # Prints: "date" (last element)
print(fruits[1:3])    # Prints: ["banana", "cherry"] (indices 1 and 2)

3. Useful List Methods

Python provides built-in methods to manipulate lists:

  • append(item): Adds an item to the end of the list.
  • insert(index, item): Inserts an item at a specified index.
  • remove(item): Removes the first occurrence of the specified item.
  • pop(index): Removes and returns the item at the given index (defaults to the last item).
  • len(list): A built-in function that returns the total count of elements.
numbers = [10, 20]
numbers.append(30)          # [10, 20, 30]
numbers.insert(1, 15)       # [10, 15, 20, 30]
last_val = numbers.pop()    # Removes 30, last_val is 30
print(len(numbers))         # Prints: 3 (elements left: [10, 15, 20])

4. List Comprehensions

List comprehensions provide a concise way to create lists from existing iterables. They act like compact, fast for loops inside brackets: [expression for item in iterable].

# Generate squares of numbers 0 to 4
squares = [n * n for n in range(5)]
print(squares)  # Prints: [0, 1, 4, 9, 16]

5. Common Beginner Mistakes

⚠️ Watch out for these mistakes:

  • IndexError: list index out of range: Trying to access an index that doesn't exist. If a list has 3 items, the maximum index is 2. `list[3]` will crash.
  • Modifying a Tuple: Writing my_tuple[0] = "new" will crash with a TypeError because tuples are immutable. Use a list instead if you need to alter values.
  • Set Unordered Expectation: Trying to index a set (e.g., my_set[0]) will crash. Sets do not have order or indexes.
Interactive Practice

Mini Practice: Shopping Cart Manager

Start with a list containing ["milk", "bread"]. Append "eggs", insert "apples" at the beginning (index 0), remove "bread", and print the remaining list sorted alphabetically. Verify your code checklist.

0% complete
Check when done
Quiz

Test Your Understanding

1. Which of the following collections is ordered and immutable?

2. What is the value of `len([1, 2, [3, 4]])` in Python?

3. Which collection type automatically eliminates duplicate entries?

🚀 Progression

Sequences are finished. Next, you'll learn how to write reusable, modular blocks of logic using **Functions**.