Introduction: Organizing Your Data
Welcome! So far, you have learned how to use variables to store single pieces of information, like a name or a score. But what if you are building an app to manage a whole class of 30 students? Creating 30 different variables would be a nightmare!
In this chapter, we explore Lists and Dictionaries—powerful containers that allow us to store, organize, and manage collections of data efficiently. We will also look at Library Functions, which are pre-written tools that save us from "reinventing the wheel." Whether you are a coding pro or just starting out, mastering these tools is essential for the H2 Computing syllabus.
Note: This chapter focuses on Module 1.2 (Programming Constructs) of your syllabus. For information on how to build your own functions, see the chapter on "Programming Constructs: Abstraction."
1. Library Functions: Your Programming Toolkit
A Library Function is a block of code written by someone else that you can "borrow" to perform a specific task. Think of it like a kitchen appliance: you don't need to know how the motor works to use a blender; you just need to know which button to press!
Common Built-in Functions
Python provides several functions that are always available:
- Input/Output: `input()` to get data from the user and `print()` to display results.
- String Operations: `len()` to find the length of a string, and methods like `.upper()` or `.lower()`.
- Mathematical Operations: Functions like `round()` or `abs()` (absolute value).
The 'import' Statement
Some tools are stored in specialized "toolboxes" called modules. To use them, you must use the `import` keyword at the top of your program.
The Math Module: Used for complex calculations. For example, to find a square root:
Example: `import math` followed by `print(math.sqrt(16))` will output \( 4.0 \).
The Random Module: Useful for simulations or games.
Example: `import random` followed by `number = random.randint(1, 10)` generates a random integer between \( 1 \) and \( 10 \).
Quick Review: Why use library functions? They make your code shorter, easier to read, and less prone to errors!
2. Python Lists: Data in a Row
A List is an ordered collection of items. Imagine a row of lockers in a school hallway. Each locker has a number (an index) and contains an item.
Key Characteristics
- Ordered: The items stay in the order you put them in.
- Zero-indexed: In Python, we start counting from \( 0 \). The first item is at index \( 0 \), the second at index \( 1 \), and so on.
- Mutable: You can change, add, or remove items after the list is created.
The "Big Four" Operations for Lists
The syllabus requires you to know how to perform these four actions:
1. Lookup (Accessing): Use the index in square brackets.
Code: \( fruits[0] \) gives you the first item.
2. Insertion: Adding new items.
- `.append(item)`: Adds the item to the end of the list.
- `.insert(index, item)`: Places the item at a specific position and shifts everything else to the right.
3. Update: Changing an existing item.
Code: \( fruits[1] = "Mango" \) replaces whatever was at index \( 1 \) with "Mango".
4. Deletion: Removing items.
- `del fruits[0]`: Removes the item at index \( 0 \).
- `.pop()`: Removes and returns the last item.
- `.remove("Apple")`: Finds the first instance of "Apple" and removes it.
Pro-Tip: If a list has \( n \) items, the last index is always \( n - 1 \). If you try to access \( fruits[n] \), Python will give you an "IndexError"!
3. Python Dictionaries: Key-Value Pairs
A Dictionary is like a real-life dictionary. Instead of looking up a word by its "position," you look it up by the word itself. In Python, we call the word a Key and the definition a Value.
Key Characteristics
- Key-Value Pairs: Every item consists of a unique key linked to a value (e.g., `"username": "Alice"`).
- Unordered: Unlike lists, dictionaries are not primarily accessed by position, but by their keys.
- Keys must be unique: You cannot have two identical keys in one dictionary.
The "Big Four" Operations for Dictionaries
Let's use a dictionary called \( student\_scores \):
1. Lookup: Use the key in square brackets.
Code: \( score = student\_scores["Bob"] \) retrieves Bob's score.
2. Insertion: Simply assign a value to a new key.
Code: \( student\_scores["Charlie"] = 85 \) adds Charlie to the dictionary.
3. Update: Assign a value to an existing key.
Code: \( student\_scores["Bob"] = 92 \) changes Bob's score to \( 92 \).
4. Deletion: Use the `del` keyword or `.pop()`.
Code: `del student_scores["Alice"]` removes Alice and her score from the record.
Did you know? Dictionaries are incredibly fast! Even if you have a million items, looking up a value by its key is almost instantaneous.
4. Choosing the Right Structure
Don't worry if you're confused about which one to use. Here is a simple rule of thumb:
- Use a List if your data is a simple sequence or if the order of the items matters (e.g., a "Top 10" leaderboard or a shopping list).
- Use a Dictionary if your data is labeled and you want to look it up by a specific name or ID (e.g., a user profile or a price list).
Common Mistake to Avoid: Using a list index for a dictionary or a string key for a list.
\( my\_list["name"] \) \(\rightarrow\) Error!
\( my\_dict[0] \) \(\rightarrow\) Error! (unless \( 0 \) is actually a key in your dictionary).
Summary Checklist
Before moving on, make sure you can:
☐ Explain what a library function is and use `import`.
☐ Perform lookup, insertion, update, and deletion on a List.
☐ Perform lookup, insertion, update, and deletion on a Dictionary.
☐ Understand that list indices start at \( 0 \).
☐ Use `math` and `random` module functions for basic tasks.
Next Step: Learn how these structures are used in more complex ways in the "Data Structures and Algorithms" section!